This is how you write a string in the memory allocated by malloc to a char pointer.
strcpy(p, "Hello");
Replace the line
p = "Hello";
with the strcpy
one & your program will work fine.
You also need to
#include <string.h>
malloc
returns a pointer to allocated memory. Say the address is 95000 (just a random number I pulled out).
So after the malloc - p will hold the address 95000
The p containing 95000
is the memory address which needs to be passed to free when you are done with the memory.
However, the next line p = "Hello";
puts the address of the string literal "Hello" (which say exists at address 25000
) into p.
So when you execute free(p)
you are trying to free 25000
which wasn't not allocated by malloc.
OTOH, when you strcpy
, you copy the string "Hello" into the address starting at p (i.e. 95000
). p
remains 95000
after the strcpy.
And free(p)
frees the right memory.
You can also avoid the malloc
and use
char *p = "Hello";
However, in this method, you cannot modify the string.
i.e. if after this you do *p = 'B'
to change the string to Bello
, it becomes an undefined operation. This is not the case in the malloc
way.
If instead, you use
char p[] = "Hello";
or
char p[10] = "Hello";
you get a modifiable string which need not be free
d.
std::string
for the semantics you would expect of a string.