Your code is reversed.
This:
char* name="Arnold";
const char* str=(const char*)malloc(strlen(name)+1);
Should look like this:
const char* name="Arnold";
char* str=(char*)malloc(strlen(name)+1);
The const
storage type tells the compiler that you do not intend to modify a block of memory once allocated (dynamically, or statically).
There is little use in dynamically allocating memory (which you are doing, based on the length of name
) and telling the compiler you have no intention of using it. Note, using meaning writing something to it and then freeing it later.
Casting to a different storage type does not fix the fact that you reversed the storage types to begin with :) It just makes a warning go away, which was trying to tell you something.
If the code is reversed (as it should be), free()
behaves as expected and you can actually use the memory that you allocate.