It seems that strtol()
and strtod()
effectively allow (and force) you to cast away constness in a string:
#include <stdlib.h>
#include <stdio.h>
int main() {
const char *foo = "Hello, world!";
char *bar;
strtol(foo, &bar, 10); // or strtod(foo, &bar);
printf("%d\n", foo == bar); // prints "1"! they're equal
*bar = 'X'; // segmentation fault
return 0;
}
Above, I did not perform any casts myself. However, strtol()
basically cast my const char *
into a char *
for me, without any warnings or anything. (In fact, it wouldn't allow you to type bar
as a const char *
, and so forces the unsafe change in type.) Isn't that really dangerous?
long int strtol(char *nptr, char **endptr, int base);
andlong int strtol(const char *nptr, const char **endptr, int base);
: this fixes your compile error. Indeed, the standard does this for other such functions, likestrchr
andstrstr
, – Calvo