函数中的malloc不能正常工作 [英] malloc in a function doesn't work well
问题描述
我不明白为什么整个事情都不起作用.
I can't understand why the whole thing doesn't work.
我只想在函数 func
中执行 malloc
,当我从函数中返回时, malloc
消失了……我得到了
I just want to do malloc
in the function func
, when I return from it, the malloc
disappears... and I get
* glibc检测到 ./test:free():无效的指针:0xb76ffff4 * *
* glibc detected ./test: free(): invalid pointer: 0xb76ffff4 **
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int func(char *p) {
p=(char*)malloc(1);
*p='a';
printf("1. p= %c\n",*p);
return 0;
}
int main()
{
char *p;
func(p);
printf("2. p= %c\n",*p);
free(p);
return 0;
}
推荐答案
char *p;
在main()处创建一个指针,您可以将其传递给另一个函数,但是可以通过值传递它,因此您在范围之外对它所做的任何更改(例如更改其指向的内容)都不会.棒".
makes a pointer local to main(), you can pass it to another function, however your passing it by value, so any changes you make to it (like changing what its pointing at) outside of the scope.won't "stick".
解决方案是将一个指针传递给一个指针,或者只是传递p的地址:
the solution is to pass a pointer to a pointer, or simply the address of p:
func(&p);
但不要忘记更改func()的参数列表!
but don't forget to change the parameter list of func()!
int func(char **p)
这篇关于函数中的malloc不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!