Re: Comments please

From: Sean Kenwrick (skenwrick_at_hotmail.com)
Date: 01/21/04


Date: Wed, 21 Jan 2004 09:10:14 +0000 (UTC)


"Christopher Benson-Manica" <ataru@nospam.cyberspace.org> wrote in message
news:bukccm$ijh$1@chessie.cirr.com...
> Sean Kenwrick <skenwrick@hotmail.com> spoke thus:
>
> > void printdate(char *date)
> > {
> > printf( "New date is %s-%s-%s\n",
> > strtok(NULL,"/"),strtok(NULL,"/")-3,strtok(date,"/")+3);
> > }
>
> > try it, it works!
>
> Okay...
>
> $ cat t.c
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> void printdate(char *date)
> {
> printf( "New date is %s-%s-%s\n",
> strtok(NULL,"/"),strtok(NULL,"/")-3,strtok(date,"/")+3);
> }
>
> int main(void)
> {
> char str[256];
> strcpy( str, "09/12/2003" ); /* strtok modifies its argument! */
> printdate( str );
> return 0;
> }
>
> $ gcc -O2 -Wall -ansi -pedantic t.c
> $ ./a.out
> Segmentation fault (core dumped)
>
> Uh oh. Looks like undefined behavior to me...
>

Just out of curiosity - what happens if you turn off optimisation? I
suspect that this is causing the parameters to be passed through registers,
not on the stack.

 I know that the standard does not define the order of parameter passing,
but I would expect the default behaviour of compilers to usually pass
parameters in reverse oder onto the stack so that variable length parameter
lists can be more easily acheived. Obviously you shouldn't ever rely on
this behavior - its just a curious side effect of compiler architecture
which I attemted to exploit in the code above....

Let me know if gcc still fails without the optimisation....

Sean



Relevant Pages

  • Re: A basic C question about segmentation fault
    ... This program terminate just after one loop while the second program ... goes on infinitely untill segmentation fault on gcc. ... I partially understand that in the second program the stack becomes ... "improper memory handling": ...
    (comp.lang.c)
  • Re: Doubt on segmentation fault
    ... generates a segmentation fault. ... the stack, the value should always be zero. ... My assumption that, insofar a resides in memory, it will ... always reside in such a 'fresh' page, was, of course, wrong. ...
    (comp.os.linux.development.system)
  • Re: pointer and storage
    ... ,stack or heap. ... You would be well-advised to use const char * rather than mere char *. ... segmentation fault is one possible result. ...
    (comp.lang.c)
  • Re: whether this is valid
    ... located in data segment which is read only. ... And your *a is a pointer (located in your stack that means it be able ... This variable pointed to address that "str" located. ... you in stack and copy "str" from data segment to that memory. ...
    (comp.lang.c)
  • tracking a segmentation fault
    ... I am trying to track a segmentation fault that's ... for the fault is that the default stack on Mac OS X is small. ... call 'unlimit stack' before I start the program, ... static int anotherarray; ...
    (comp.lang.c)