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

时间:2014-02-03 02:33:53

标签: 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中做到这一点的方法吗?因为它编译但崩溃了 崩溃细节:Unhandled exception at 0x00c610a9 in 11.exe: 0xC00000FD: Stack overflow. 因为在CODE BLOCKS中它完美无缺

问题是:为什么它在代码块中工作,但在VS2010中却没有

2 个答案:

答案 0 :(得分:3)

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

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

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

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

答案 1 :(得分:0)

好的函数原型应该是func1(Set ** a)