Re: a few doubts!
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 30 Apr 2005 20:02:16 GMT
SM Ryan <wyrmwif@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx> writes:
> "maadhuu" <madhu_ranjan_m@xxxxxxxxx> wrote:
> > #include<stdio.h>
> > #include<conio.h>
> > #include<string.h>
> > main()
> > {
> > char * a= "bcd";
> > clrscr();
> > strcpy(a,"hello");
> > a = "fgh";
> > a[0] = 't';
> > printf("%s",a);
> > }
>
> Some compilers allow strings to be overwritten by placing them in
> read-write memory sometimes with the expectation the string can be
> modified. Writing outside an array bounds does not necessarily
> trigger a fault action.
>
> The code results are machine and compiler dependent.
[ Non-traditional '#' quoting character changed to '>'. ]
[ Excessively long lines reformatted. ]
[ Becoming seriously annoyed by gratuitously non-traditional formatting. ]
To be precise, an attempt to modify a string literal invokes undefined
behavior. An implementation is allowed to place string literals in a
read-only memory segment, causing a trap whenever the program attempts
to write to them. It's also allowed to place them in read-write
memory, and even to share the same memory for different occurrences of
the same string. For example, this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *s = "hello, world\n";
strcpy(s, "HAHA!\n");
printf("hello, world\n");
return 0;
}
could legally do any of the following:
Blow up on the strcpy() call (perhaps with a segmentation fault).
Print "hello, world".
Print "HAHA!".
Print "You have invoked undefined behavior and your mother wears army boots."
Make demons fly out your nose.
Some compilers may have an an option to control whether string
literals are stored in read-only or read-write memory. Such an option
is useful mostly to diagnose this kind of problem (or, if you're
desparate, to work around it). The only real solution is to avoid
writing to string literals in the first place.
One oddity is that, for historical reasons, a string literal is not
treated as "const". If it were, the compiler would be required to
diagnose most cases of this error.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- a few doubts!
- From: maadhuu
- Re: a few doubts!
- From: SM Ryan
- a few doubts!
- Prev by Date: Re: about malloc, realloc and free
- Next by Date: Re: Using define with variable values
- Previous by thread: Re: a few doubts!
- Next by thread: typedef struct
- Index(es):
Relevant Pages
|