问题
I can't understand why the whole thing doesn't work.
I just want to do malloc
in the function func
, when I return from it, the malloc
disappears... and I get
* 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;
}
回答1:
char *p;
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".
the solution is to pass a pointer to a pointer, or simply the address of p:
func(&p);
but don't forget to change the parameter list of func()!
int func(char **p)
回答2:
While in func, p is a copy of the pointer you passed to it, so p is created inside func and deleted when func is finished.
You have two solutions :
- Pass a pointer to the pointer, a char **p, and do
*p = malloc(1)
, then func will accept a char **p - Return the alloced variable un func and assign it :
p = func();
回答3:
pass &p
in main means call func as func(&p)
change the function sugnature of func(char *p)
to func(char **p)
Thep
in func
is the local one to that func
so when func
exits it destroyed and also leads to memory leak.
And in main you are freeing a pointer which is not pointing to memory allocated by malloc
, calloc
so free(p)
is Undefined behaviour
in this case and it's not freeing that memory which you have allocated in func
so it's memory leak
1st method:
void func(char **p)
{
*p=malloc(1);
//rest of your code here
}
int main()
{
int *p;
func(&p);
// your code here
free(p);
}
2nd method : It's easy no use of **
char * func(char *p)
{
p=malloc(1);
// rest of code here
return p;
}
int main()
{
char *p;
p=func(p);
//rest of code here
free(p);
}
来源:https://stackoverflow.com/questions/13541990/malloc-in-a-function-doesnt-work-well