I'm (obviously) learning C
I don't understand why would I use malloc
to allocate memory for a newly copied string (they did it in cs50 memory lecture)
#include <stdio.h>
#include <stdlib.h>
int main(){
char *s = "Hi";
char *t; // Why the need for char *t malloc(3) here ??
strcpy(t,s);
printf("%s",t); // prints "Hi"
return 0;
}
CodePudding user response:
The first declaration: char *s = "Hi";
does not need a malloc because at compile time, the compiler will set s
to be pointing at a string literal that will already have a designated place in memory.
The second declaration: char *t;
does not get assigned to point at anything. You COULD copy the contents of s
into t
and maybe everything would work, but you would be copying the contents of s
into some random section of memory that t
is initially pointed to which your your OS hasn't allocated to you. Most likely causing a segfault and crashing.
That's what malloc does, it makes a request for a number of bytes to be allocated to your program on the heap, then returns a pointer to the starting address of that memory (or NULL if it failed to allocate memory for any reason), allowing you to safely use it if the request succeeded.