0

The code looks something like this

void otherfunc(char* str) {
    str = malloc(128);
    // Initialize str to something
}

void mainfunc() {
    char* foo = NULL;
    
    otherfunc(foo);
    
    free(foo);
}

Ideally, foo should be freed, right? I'm not sure why this is leaking. Also, if I move the free() to otherfunc it does not leak.

  • Running that code in a debugger would show you within seconds that `foo` is still `NULL` when you free it. You should get used to using a debugger. – Gerhardh Mar 19 '22 at 17:20

1 Answers1

0

You are passing the pointer by value, the pointer returned by malloc is lost when you exit the function, a correction to your code should be

void otherfunc(char** str) {
    *str = malloc(128);
    // Initialize str to something
}

void mainfunc() {
    char* foo = NULL;
    
    otherfunc(&foo);
    
    free(foo);
}
Paul_0
  • 358
  • 4
  • 11