#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* f(void) {
char *x;
x = malloc(sizeof(char) * 4);
strcpy(x, "abc");
return(x);
}
int main(void) {
char *a;
a = f();
printf("%s", a);
free(a);
return(0);
}
Does the variable x
in the function have to be freed? If so, how is that possible when I need to return it?
Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc().
delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
Freeing the allocated memory deallocates it and allows that memory to be used elsewhere while the pointer to where the memory was allocated is preserved. Setting a pointer to the allocated memory to NULL does not deallocate it.
Does the variable x in the function have to be freed?
Yes (kinda, see my later comment). Every call to malloc
requires a later call to free
. Otherwise, you have a leak. Remember though; you are not "free[ing] x
", you are freeing the memory that x refers to.
When you return x
a copy of the value (an address) of x
is made and returned to the caller. x
was declared with automatic storage duration. It is the memory it refers to that must be freed.
If so how is that possible when I need to return it.
Your design has placed the onus on the caller to free the memory. You have already done this in main. Of course, using this method requires that you document the function so that users of your code know that they are receiving an address to memory which was dynamically allocated.
A better approach (IMO) is to take a buffer as an input parameter. Now it is very clear who is responsible for managing this memory (i.e., the caller). Perhaps I don't even want to dynamically allocate it. With this design it is my choice.
void f(char *buf, size_t buf_size) {
strncpy(buf, "abc", buf_size - 1);
buf[buf_size-1] = '\0';
}
On a side note, you should always be checking the return value of malloc
. It can fail, in which case a null pointer will be returned. Also, sizeof(char)
is guaranteed to be 1
by the standard, so you can remove that bit and just say malloc(n)
.
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