Re: I don't understand why the compiler does this.



On 09/01/2006, Chad wrote:

> The following code was taken from comp.lang.c
>
> #include <string.h>
> #include <stdio.h>
>
> int manip(char *str) {
> str[0] = 'A';
> str[1] = 'B';
>
> return 0;
> }
>
> int main(void){
> char my_string[] = "thisisokay";
>
> manip("thisisbad");
> printf("The modified value is: %s\n",my_string);
>
> /*manip("thisisbad");*/
>
> return 0;
> }
>

You've passed a literal string to a function which then tries to modify
it. The effect of trying to modify a string literal is undefined. The
compiler might choose to store the string literal in memory marked as
read-only. If you program tries to modify read only memory it will
crash.

--
Simon Elliott http://www.ctsn.co.uk
.



Relevant Pages