when to carefully use free() to free up malloc() used memory?

后端 未结 3 1819
谎友^
谎友^ 2020-12-10 18:51

I read from many question here in SO and some other articles regarding free() function in c that frees the memory of unused variables. In my case, I have the following code

3条回答
  •  被撕碎了的回忆
    2020-12-10 19:20

    No you shouldn't free strC inside this function because it is the return value of this function. If you do so the statement:

    return strC;
    

    will return some unexpected or garbage value.

    char* stringA = injectStrAt(str, strToIn, pos);
    printf("StringA: %s"); // unexpected value.
    

    So when should you free up the memory? Well, you should do it after the value of strC is returned from the function injectStrAt() to stringA, in this particular case. Although generally memory is freed when the string or the variable to which the memory was allocated is no longer required.

    char* stringA = injectStrAt(str, strToIn, pos);
    /... use the string
    
    free(stringA);
    

提交回复
热议问题