函数调用中的Malloc似乎在返回时被释放? [英] Malloc inside a function call appears to be getting freed on return?
问题描述
我认为我已经将其归结为最基本的情况:
I think I've got it down to the most basic case:
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * arr) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
输出是这样的:
> ./a.out
car[3]=-1869558540
a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
being freed
*** set a breakpoint in malloc_error_break to debug
>
如果有人能阐明我的理解失败的地方,将不胜感激.
If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.
推荐答案
您按值传递指针,而不是按引用传递指针,因此,在foo内部对arr所做的任何操作都不会在foo函数之外产生任何影响. 正如m_pGladiator所写的那样,一种方法是这样声明对指针的引用(仅在C ++中可用,btw.C不知道引用):
You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function. As m_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references):
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * &arr ) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
另一种(更好的恕我直言)的方法是不将指针作为参数传递而返回指针:
Another (better imho) way is to not pass the pointer as an argument but to return a pointer:
int main(int argc, char ** argv) {
int * arr;
arr = foo();
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
int * foo(void ) {
int * arr;
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
return arr;
}
您可以将指针传递给指针.这就是引用传递的C方法.语法有点复杂,但是很好-这就是C的方式...
And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is...
int main(int argc, char ** argv) {
int * arr;
foo(&arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int ** arr ) {
(*arr) = (int*) malloc( sizeof(int)*25 );
(*arr)[3] = 69;
}
这篇关于函数调用中的Malloc似乎在返回时被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!