I'm currently learning about how to use pointers and memory allocation in C, and writing a simple code snippet to try to print a string using pointers. What I have now is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *aString(void)
{
char str[20];
strcpy(str, "Hello World!");
return str;
}
int main(int argc, char **argv)
{
char *ptr = malloc(20);
ptr = aString();
printf("%s\n", ptr);
free(ptr);
exit(0);
}
Which just prints an empty line and tells me that the call to free uses an invalid pointer . Could anyone take the time to explain where I'm thinking about things the wrong way?
Edit: Thank you for all the answers, I am reading through them all.
freecan only be used on space allocated bymalloc(and friends). The lineptr = aString();means to pointptrat a different place than the malloc'd block. It doesn't mean to copy characters .str[]is a local variable, on the stack. when it goes 'out of scope', I.E. when the function exits, any access of the variable is undefined behaviour and can lead to a seg fault event. My suggestion: Declare the str[] array in main() and pass a pointer to str[] to the aString() function