Dynamic Memory Allocation

advertisements

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:

char* str = (char*)malloc(20*sizeof(char));

Then, you assign a string literal to str. This will overwrite what str held 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 dereference str, as in str[0] = 'A'; str[1] = '\0';.

str = "This is a string";

So, what is the value of str now? 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 to str = (char*)0x1234, where 0x1234 is supposed to be the address at which the compiler has put the string literal.

That explains why this works well:

char* str = "This is a string";

Please also note that the static memory is not to be changed at runtime, so you should use const char* for this assignment.

So in which case we have to allocate memory space?

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.