简体   繁体   中英

malloc in a function doesn't work well

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

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 :

  1. Pass a pointer to the pointer, a char **p, and do *p = malloc(1) , then func will accept a char **p
  2. Return the alloced variable un func and assign it : p = func();

pass &p in main means call func as func(&p) change the function sugnature of func(char *p) to func(char **p)

The p 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM