sách gpt4 ai đã đi

C 自由() : invalid pointer allocated in other function

In lại 作者:行者123 更新时间:2023-11-30 17:25:54 30 4
mua khóa gpt4 Nike

我是 StackOverflow 的新人。我现在正在学习C指针。

Đây là mã của tôi:

#include 
#include

int alloc(int* p){
p = (int*) malloc (sizeof(int));
if(!p){
puts("fail\n");
trả về 0;
}
*p = 4;
printf("%d\n",*p);
return 1;
}

int main(){

int* pointer;

if(!alloc(pointer)){
return -1;
}khác{

printf("%d\n",*pointer);
}

free(pointer);

trả về 0;
}

我编译:gcc -o main main.c

错误:free():无效指针:0xb77ac000 ***

我的代码有什么问题吗?

1 Câu trả lời

C 中的参数luôn luôn按值传递。因此,当您调用 alloc(pointer) 时,您只需传入 con trỏ 包含的任何垃圾值。在函数内部,赋值 p = (int*)... 仅修改局部变量/参数 P。相反,您需要将con trỏcủa地址传递给alloc, như được hiển thị bên dưới:

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;
}

在 main 中,您可以像这样调用 alloc:

if (!(alloc(&pointer))) {
....

然后,您的代码就可以工作了。

关于C 自由() : invalid pointer allocated in other function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948668/

30 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com