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;
}
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:
but don’t forget to change the parameter list of func()!