I have a small confusion in the dynamic memory allocation concept.
If we declare a pointer say a char pointer, we need to allocate adequate memory space.
char* str = (char*)malloc(20*sizeof(char));
str = "This is a string";
But this will also work.
char* str = "This is a string";
So in which case we have to allocate memory space?
String literals are a special case in the language. Let’s look closer at your code to understand this better:
First, you allocate a buffer in memory, and assign the address of that memory to
str:Then, you assign a string literal to
str. This will overwrite whatstrheld previously, so you will lose your dynamically allocated buffer, incidentally causing a memory leak. If you wanted to modify the allocated buffer, you would need at some point to dereferencestr, as instr[0] = 'A'; str[1] = '\0';.So, what is the value of
strnow? The compiler puts all string literals in static memory, so the lifetime of every string literal in the program equals the lifetime of the entire program. This statement is compiled to a simple assignment similar tostr = (char*)0x1234, where0x1234is supposed to be the address at which the compiler has put the string literal.That explains why this works well:
Please also note that the static memory is not to be changed at runtime, so you should use
const char*for this assignment.In many cases, for example when you need to modify the buffer. In other words; when you need to point to something that could not be a static string constant.