4 Sep 2002 redi   » (Master)

mathieu: I was only half paying attention. Yes, line 3 might not behave as expected. You probably know this already, but I'm explaining for my own benefit as much as anything! The array initialisation in line 2 creates an array on the stack, of size strlen("this is a string you can modify")+1, and copies the characters in the string literal into the array. Line 1 assigns the address of the string literal to p. a is therefore an array of non-const chars that can be modified and line 3 is fine. p points to the actual string literal, which is an array of non-modifiable chars and so line 4 invokes undefined behaviour (on my OS the literal is in the text section of the executable, which can't be modified, but that's an implementation detail).

I agree that the code shouldn't be valid; if string literals in C had type const char [] instead of being "non-modifiable char" [] the problem wouldn't exist. Bjarne Stroustrup's doing an interesting series of articles in the C/C++ Users Journal at the moment about C/C++ compatibility and why C++ retains this sort of gotcha from C, rather than fixing the mistake and abandoning compatibility.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!