When to use free () carefully to free malloc () memory?

I read a lot of questions here in SO and some other articles regarding the free () function in c, which frees up memory of unused variables. In my case, I have the following block of code.

char *injectStrAt(char *str, char *strToIn, int pos)
{
    char *strC = malloc(strlen(str) + strlen(strToIn) + 1);
    strncpy(strC, str, pos);
    strC[pos] = '\0';
    strcat(strC, strToIn);
    strcat(strC, str + pos);
    return strC;
}

The above function, which I use to input a string block into an array. I use mallocto create a new one char*. In the case above, do I need to do free(strC)? consulting services.

+4
source share
3 answers

strC - , free(strC) . , , .

+6

strC, , , free() . , , .

.

+3

, strC , . :

return strC;

.

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

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

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

free(stringA);
+2
source

Source: https://habr.com/ru/post/1530965/


All Articles