Ok, you dynamically allocate 10 bytes. Then you make the “name” variable (a char pointer) point to that dynamically allocated block. Then you make a char pointer which points to the same dynamically allocated block that “name” points to. Then you “free(name)” which deallocates the block that “tmp_name” also points to. “name” and “tmp_name” both point to deallocated memory that may have been taken over by another program, essentially returning a pointer pointing to trash value. I recommend this:
#include <stdio.h>
#include <stdlib.h>
char* namefunct(void);
int main(int argc, char* argv[])
{
char* my_name = namefunct();
printf("Hello, %s!!!\n", my_name); //namefunct is not returning tmp_name
free(my_name);
return 0;
}
char* namefunct(void)
{
char* name = malloc(sizeof(char) * 10);
scanf("%s", name);
return name;
}
or, just like @Siddhant posted, you could make name a global variable and free it after
solved Can any one please help me what wrong with this code? [closed]