Re: gcc bug?
From: Arthur J. O'Dwyer (ajo_at_nospam.andrew.cmu.edu)
Date: 11/07/03
- Next message: Arthur J. O'Dwyer: "Re: Is buf[n]++ a lvalue?"
- Previous message: Eric Sosman: "Re: Segmentation Fault on Linux, but not on Solaris"
- In reply to: Victor Irzak: "gcc bug?"
- Next in thread: Eric Sosman: "Re: gcc bug?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 7 Nov 2003 15:48:02 -0500 (EST)
On Fri, 7 Nov 2003, Victor Irzak wrote:
>
> This program causes seg fault on gcc, but executes fine on icc and VC7.
> Is there a reason for it or is it a bug?
Yes. It's a bug in your program.
> Note: if "char * const str" is changed to "char * str",
> the gcc problem disappears.
The bug is still present even with the 'const' removed.
> #include "stdio.h"
Should be
#include <stdio.h>
>
> int main() {
> char * const str="ya";
'str' points to the string "ya", which is stored somewhere
off in memory, possibly in ROM (think: a segment to which your
program cannot write).
> char *first = &str[0], *second =&str[1];
'first' and 'second' also point into that same string, in
read-only memory. By the way, do you understand that
char *first = str, *second = str+1;
would be equivalent to the line above?
> char tmp;
>
> printf("%s\n", str);
Prints the string "ya". This is fine, so far.
> tmp = *first;
> *first = *second;
Here's your bug. You try to assign a new value to
the char object pointed to by 'first' -- and that
object is off in read-only memory. You can't modify
string literals in C.
This is where the program segfaults with GCC.
> *second = tmp;
A second bug.
>
> printf("%s\n", str);
>
> return 0;
> }
To make your program work as expected, and remove
the undefined behavior, you could create an array
local to 'main' in which to store your string:
char str[] = "ya";
(then proceed as above). See this newsgroup's
FAQ for more information.
-Arthur
- Next message: Arthur J. O'Dwyer: "Re: Is buf[n]++ a lvalue?"
- Previous message: Eric Sosman: "Re: Segmentation Fault on Linux, but not on Solaris"
- In reply to: Victor Irzak: "gcc bug?"
- Next in thread: Eric Sosman: "Re: gcc bug?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|