07-01-07 12:21 AM
Ravi <ra.ravi.rav@gmail.com> wrote:
> #include <stdio.h>
> int *p;
> int main(void)
> {
> *p = 10;
> int pid;
> pid = fork();
> if(pid==0) {
> *p=20;
> printf("child process: pid = %d; p = %p; *p =
> %d",getpid(),p,*p);
> } else {
> printf("\nchild process: pid = %d; p = %p; i =
> %d",getpid(),p,*p);
> }
> }
> the code gives seg fault.
This is your (first) problem:
> int *p;
> *p = 10;
'p' is a pointer that, since it's a variable with file scope, is
initialized to NULL, an address you are not allowed to write to
(if it would be a pointer within a function it might even be
worse since it would instead be uninitialized, i.e. point to a
completely random place in memory you are also rather likely
not allowed to write to or, worse, pointing to some address
with important data of your program, so writing to it would
overwrite those data). When you now try to store a value at
the address stored in the pointer (NULL) the system recognizes
that you have no permission to write there and stops your pro-
gram with a segmentation fault (segmentation faults typically
indicate that you were trying to use memory you're not allowed
to or that doesn't exist).
If you want to store something via 'p' you need first to make
'p' point to an address with memory you "own", i.e. do
int storage;
int *p = &storage;
etc. (or allocate memory that 'p' is then pointing to). Another
nit-pick: the '%p' format specifier expects a void pointer for
printing, so you should do
printf( "child process: pid = %d; p = %p; *p = %d",
getpid(), (void *) p, *p );
i.e. cast 'p' to (void *) when you use it in this printf()
call.
And, a final nit-pick: you promised that main() returns an
integer, but your main() function doesn't end in a return.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
[ Post a follow-up to this message ]
|