Home:ALL Converter>C - freeing memory allocated in function

C - freeing memory allocated in function

Ask Time:2012-11-18T12:02:10         Author:user10099

Json Formatter

I have a function that allocates string and returns its pointer. When I use it directly in call of other function, do I need to free the memory?

For example:

char *getRow(){
     char *someString = (char*) malloc(sizeof(char) * 10);
     strcpy(someString , "asdqwezxc");
     return someString;
}

int main(){
     printf("%s", getRow());
}

What happens with memory allocated in that function? Is there any way to free it or do I need to store it to some variable before using it?

Author:user10099,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/13437363/c-freeing-memory-allocated-in-function
Sidharth Mudgal :

Even if you have returned from the function, the memory is not deallocated unless you explicitly do so. So you must store the return value and call free.\n\nint main(){\n char* str = getRow();\n printf(\"%s\", str);\n free(str);\n}\n",
2012-11-18T04:06:02
David Buck :

You need to store it in a variable, use it, then free it. If you don't free it you get a memory leak.",
2012-11-18T04:08:54
yy