Ç免费():无效的指针在其他功能分配 [英] C free(): invalid pointer allocated in other function
问题描述
我在StackOverflow的是新。我学习C指针现在。
I'm new in StackOverflow. I'm learning C pointer now.
这是我的code:
#include <stdio.h>
#include <stdlib.h>
int alloc(int* p){
p = (int*) malloc (sizeof(int));
if(!p){
puts("fail\n");
return 0;
}
*p = 4;
printf("%d\n",*p);
return 1;
}
int main(){
int* pointer;
if(!alloc(pointer)){
return -1;
}else{
printf("%d\n",*pointer);
}
free(pointer);
return 0;
}
我编译:gcc的-o主要的main.c
I compile with: gcc -o main main.c
错误:免费():无效的指针:0xb77ac000 ***
error: free(): invalid pointer: 0xb77ac000 ***
这有什么错我的code?
what's wrong with my code?
推荐答案
用C参数是始终通过按值。所以,当你调用页头(指针)
,你只是传递任何垃圾值指针
包含。在函数内部,分配 P =(INT *)...
只修改局部变量/参数<code> P 。相反,你需要指针
的地址的传递到页头
,就像这样:
Arguments in C are always passed by value. So, when you call alloc(pointer)
, you just pass in whatever garbage value pointer
contains. Inside the function, the assignment p = (int*)...
only modifies the local variable/argument p
. Instead, you need to pass the address of pointer
into alloc
, like so:
int alloc(int **p) {
*p = malloc(sizeof(int)); // side note - notice the lack of a cast
...
**p = 4; // <---- notice the double indirection here
printf("%d\n", **p); // <---- same here
return 1;
}
在主,你会叫页头
是这样的:
In main, you would call alloc
like this:
if (!(alloc(&pointer))) {
....
然后,您的code会工作。
Then, your code will work.
这篇关于Ç免费():无效的指针在其他功能分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!