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). Freeing memory is modifying it. Note, you don't need to cast the return value of malloc(), but that's just an aside.
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 (optionally) 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()
will work as expected since you can actually modify the memory that you allocated.