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.

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 do we have to allocate memory space?

Both are wrong. In the first case you allocate 20 bytes of space for a string. However, instead of saving a string in that space, you change the pointer to point to a static, non-mutable string. The only difference to the second example is that you don't allocate space that you'll never be able to free again.

The correct way would be this:

char *str = (char *) malloc(20 * sizeof(char));
strncpy(str, "This is a string", 20 * sizeof(char));

A pointer isn't a magical type that knows what you want it to do. It's just a numerical type with extra operators, = still means=. Ergo, when you use = on it, you're telling it to point to a completely different spot in memory. If you want to preserve memory you already have, you have to use string operations or array operations to copy it in.