Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - freeing memory allocated in function

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?

like image 217
user10099 Avatar asked Nov 18 '12 04:11

user10099


1 Answers

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.

int main(){
    char* str = getRow();
    printf("%s", str);
    free(str);
}
like image 169
Sidharth Mudgal Avatar answered Sep 18 '22 05:09

Sidharth Mudgal