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.