在 C 中的另一个函数调用的函数中使用 malloc 会导致崩溃 [VS2010]

标签 c malloc

我想在函数中调用 malloc,并且我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#define maxLength 4
typedef short int *set;


    void func(set *a)
    { 
      func1(a);
    }

    void func1(set *a)
    {
        *a=malloc(maxLength*sizeof(set));
        (*a)[0]=10;
        (*a)[1]=13;
        (*a)[2]=15;
    }

    void main()
    {
        set a;
        func(&a);
        printf("%d %d %d",a[0],a[1],a[2]);

    }

VS2010代码:

#include <stdlib.h>
#include "stdafx.h"
#include <stdio.h>
#include "12.h"
#define maxLength 4
typedef int *set;


void func(set *a){
    func(a);
}

void func1(set *a){
        *a=reinterpret_cast<set>(malloc(maxLength*sizeof(set)));
               (*a)[0]=10;
               (*a)[1]=13;
               (*a)[2]=15;
}

这是在VS2010中实现的方法吗?因为它编译但崩溃了 崩溃详细信息:11.exe 中 0x00c610a9 处出现未处理的异常:0xC00000FD:堆栈溢出。 因为在代码块中它工作得非常完美

问题是:为什么它在代码块中有效,但在 VS2010 中无效

最佳答案

在你的 VS 代码中你有这个:

void func(set *a){
    func(a);
}

这是一个非终止递归,因此会发生堆栈溢出。

FWIW,您显然正在将代码编译为 C++,因为您使用 reinterpret_cast<set>仅在 C++ 中有效。

关于在 C 中的另一个函数调用的函数中使用 malloc 会导致崩溃 [VS2010],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518891/

相关文章:

c - Malloc header 内容

c - 使用 mongoose 通过 websockets/http 将图像/文件/音频文件发送到浏览器

c - 为什么我的阶乘程序可以运行,但我几乎相同的 pow 程序却无法运行?

c - 分配之间的差异

c - 返回到 if 语句的开头

c++ - 使用 C++ 编译器编译 C 代码

C: malloc,结构错误

c - 填充结构数组并在堆上分配内存

ios - -[NSString dataUsingEncoding :] gives garbage at end of string in iOS 9, 不是 iOS 8

c - 指向 char 到 char 数组的指针