Search code examples
cmallocfree

Using malloc like this is correct?


I am new to dynamic memory allocation. Does this type of use create any memory leak or unallocated memory access?

char *func2(char *str) {
    //Do something like writing 10 characters to str
    return str;
}

void func1() {
    char *str = NULL, *res;
    int len = 10;
    str = (char *)malloc(len * sizeof(char));
    res = func2(str);
    free(str); 
    printf("%s", res);
}

Does the final printf statement in func1 result in segmentation fault as str is already freed, will res be a dangling pointer, with no memory location to point?


Solution

  • res is used after the memory it references is freed. This is undefined behavior, which may or may not lead to a runtime error. Undefined behavior is undefined, after all.

    What I think is likely to happen, in practice, is that your program will happily print whatever is in the memory res points to. That memory isn't gone, you've just said you wouldn't use it anymore. What will be in that memory is uninitialized garbage, since you never wrote anything to it. I think you'll get gobbledygook for output.