我想在函数中调用 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/