On Wednesday 09 March 2005 20:57, Diego Iastrubni wrote:
> See notes inside.
>
> Tzahi Fadida wrote:
> >As we talked about in the c with a spoon lecture, I tried the
> >pointer arithmetic and then free and at least for me it didn't
> >work.
> >gcc version egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)
> >
> >[EMAIL PROTECTED]:~]$ gcc nis2.c
>
> "make nis2 " quite easier no?
>
What difference does it make for a single-file program? What is disturbing,
though is that he's working as root.
> >[EMAIL PROTECTED]:~]$ ./a.out
> >char y[0] a
> >char y[1] b
> >char y[2] c
> >char y[3] d
> >Segmentation fault (core dumped)
>
> of course... you are messing with wrong memory locations.
>
> >#include <stdio.h>
> >#include <stdlib.h>
> >main(){
> > char *y = (char *)malloc(4*sizeof(char));
>
> lets assume y is 100 (the allocated memory is found at "100", at least
> in this run)
>
> > char *x = y + 2;
>
> x = 100 + 2;
>
> > y[0]='a';
>
> mem[102] = a <- ok
>
No. That's mem[100] = 'a'. y == 100, and is the pointer to the beginning of
the allocated memory.
> > y[1]='b';
>
> mem[103] = b <- ok
>
mem[101] = 'b'.
> > y[2]='c';
>
> mem[104] = c <- ok
>
mem[102] = 'c'.
> SEGFAULT! the allocated memory is found at memory 100-103. Bad Thazi!
>
No, it's OK so far.
> In real life Linux does 'allow' the execution of this program, as it
> printed lines after this point. Can anyone explain?
>
> > y[3]='d';
>
> we know whats wrong here...
>
This is still OK.
> > printf("char y[0] %c\n", y[0]);
> > printf("char y[1] %c\n", y[1]);
> > printf("char y[2] %c\n", y[2]);
> > printf("char y[3] %c\n", y[3]);
> >
> > free(x);
>
> free( 102 ) .... wait... 102 is not allocated! 100 was allocated!
>
> IMHO this is the line that really segfaults.
>
Probably.
Regards,
Shlomi Fish
---------------------------------------------------------------------
Shlomi Fish [EMAIL PROTECTED]
Homepage: http://www.shlomifish.org/
Knuth is not God! It took him two days to build the Roman Empire.
--------------------------------------------------------------------------
Haifa Linux Club Mailing List (http://www.haifux.org)
To unsub send an empty message to [EMAIL PROTECTED]