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?

[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

     y[1]='b';

mem[103] = b <- ok

     y[2]='c';

mem[104] = c <- ok

SEGFAULT! the allocated memory is found at memory 100-103. Bad Thazi!

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...


     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.

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]);
exit(EXIT_SUCCESS);
}


exit(EXIT_SUCCESS);

Optimism is a good thing, don't loose it.








-------------------------------------------------------------------------- Haifa Linux Club Mailing List (http://www.haifux.org) To unsub send an empty message to [EMAIL PROTECTED]




Reply via email to