Dynamic Memory Allocation

Hello Guys

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.

1
2
char* str = (char*)malloc(20*sizeof(char));
str = "This is a string";


But this will also work.

 
char* str = "This is a string";

In which case we have to allocate memory space?
Last edited on
Anything wrapped in double quotes, such as "This is a string" is a string literal. These are handled specially by the compiler. They are of type array of n const char and are given static storage duration.

This means that they exist throughout the entire duration of the program. The memory for them is handled for you by the compiler.
What is more malloc is c function. In latest c++ standard there is new and new[] (for arrays) and delete delete[] operators/functions for memory allocations and both of them are working much better and they are easier to use.
In your first example, you actually have a memory leak. You allocated 20 bytes of dynamic memory and assigned "str" to point to them. You then reassigned "str" to point to a string literal, leaving the allocated dynamic memory unreferenced.

I believe you were looking to place "This is a string" into the memory that you allocated. To do so, look at strcpy and strncpy. Also consider sprintf and snprintf. These are all C function. In C++ it is better to use the string class. The string class hides all of the dynamic memory work, and it allows you to assign the value of the string using the "=" operator.
Topic archived. No new replies allowed.