char *p, *y;
const char *x ;
p = (char *) malloc(5);
snprintf(p, 4, "test");
x = p;
y = (char *) x;
snprintf(y, 4, "abcd");
Can we cast const char * to char * and change the contents?
Thanks Kumar
char *p, *y;
const char *x ;
p = (char *) malloc(5);
snprintf(p, 4, "test");
x = p;
y = (char *) x;
snprintf(y, 4, "abcd");
Can we cast const char * to char * and change the contents?
Thanks Kumar
Depending on the compiler warning level it may cause build break. If it is not causing a build break because your warning level is low then I guess you better be sure that you are trying to manipulate a var that other developers would think it is a constant!!
Also keep in mind you will end with non null terminated strings here, Always remember I am writing this code for a company and other developers would touch it sooner or later. So stick to the normal coding standards and avoid any mysterious code that may waste your college's time or your time in the future.
While in this situation it is safe, as we know that the value pointed to by x
is not const
ant. It is generally not safe to cast a const char *
to char *
and then change its contents. That's what the const
qualifier is for: it indicates to compiler that the value that the pointer points to will not – and the compiler will make sure that it cannot – be changed. In some cases the compiler can then store this in read-only memory and so changing it then would likely cause segmentation faults.
If we remove the cast from the assignment we get the following warning:
warning: assignment discards 'const' qualifier from pointer target type
But with the cast you're basically telling the compiler that you know better and it will obey.
A (trivial) case where this would go disastrously wrong is as such:
const char * x = "Hello world!";
// If I now try to change x the compiler will throw an error
char * y = (char *) x; // <-- cast curbs compiler complaints
// I can now change y (and through it x) which will cause undefined behaviour
// as the string in x is most likely placed in read-only memory
y[0] = 'h'; // <-- Problems!
In the end, if you ever need to do this you should really consider what is really going on in your program.
The C standard does permit you to cast away the const qualifier.
You may use the resulting pointer to modify the pointed-to object if it was not originally defined as const and is not a string literal. The behavior is not defined if the object was defined as const or is a string literal.