I was just wondering, in the following scenarion, is the memory used by 'stringvar' freed after method1 is done executing?
// Just some method
void method2(char* str)
{
// Allocate 10 characters for str
str = malloc(10 * sizeof(char));
}
// Just another method
void method1()
{
char* stringvar;
method2(stringvar);
// Is the memory freed hereafter, or do I need to call free()?
}
I ask, because if I put a 'free(stringvar)' at the end of method1, I get a warning that stringvar is unitialized inside method1 (which is true).
No, the memory is not deallocated after method1
, so you'll have a memory leak. Yes, you will need to call free
after you're done using the memory.
You need to send a pointer to a pointer to method2
if you want it to allocate memory. This is a common idiom in C programming, especially when the return value of a function is reserved for integer status codes. For instance,
void method2(char **str) {
*str = (char *)malloc(10);
}
char *stringvar;
method2(&stringvar);
free(stringvar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With