warning: function returns address of local variable [-Wreturn-local-addr]
This warning occurs when a function in C returns the address of a local variable. The warning is indicating that returning the address of a local variable can lead to undefined behavior.
To fix this warning, you should avoid returning the address of a local variable from a function. Instead, consider allocating memory dynamically using functions like malloc()
or calloc()
, and returning the pointer to the dynamically allocated memory.
Here's an example of how you can fix this warning:
#include <stdlib.h>
int* createArray(int size) {
int array = malloc(size sizeof(int));
return array;
}
In the example above, we allocate memory dynamically using malloc()
to create an array, and then return the pointer to the allocated memory. This avoids returning the address of a local variable and resolves the warning.
Remember to free the dynamically allocated memory using free()
when you're done using it to avoid memory leaks.