Hi everybody.

I need to pass the value of a pointer to a struct for a server program to a client program.

my code is the following

for the server:

write(ns, &fixedparkpnt, sizeof(fixedparkpnt));

write(ns, &fixeddriverpnt, sizeof(fixeddriverpnt));

and for the client:

read(sock2, &fixedparkpnt, sizeof(fixedparkpnt));
read(sock2, &fixeddriverpnt, sizeof(fixeddriverpnt));

sock2 is the socket for the comunication and fixedparkpnt and fixeddriverpnt are the pointers to the structs named parking and customer accordingly. the structs are in shared memory segments. after the read() commands i have a

printf("Data recieved\n");

for debugging purposes and the client prints it. when i ask it to print (*fixedparkpnt).name (member of the struct parking) it gives me a segmentation fault

Recommended Answers

All 4 Replies

Why does it seg fault? Because you have to send the value that the pointer points to and not the pointer.

int *iptr = (int*)malloc(sizeof(int));
*iptr = 1234;

/*the wrong way*/ 
write(sock_var, iptr, sizeof(iptr));

/*the right way*/
write(sock_var, *iptr, sizeof(int));

Note - pointers are only valid in their own address space.

A few questions...This client server program, do they reside on the same computer and do they use Unix sockets? Because if they do you should be passing values used in functions like shmat() which requires shared memory id....once you attach, your pointing to the shared memory.

They are in the same PC and i'm using sockets and shared memory and i have other pointers for that which i copy to the pointers fixedparkpnt and fixeddriverpnt. The thing is, i want to pass the address that the pointers hold and not their values because they point to the first address of shared mem segments that contain structures. Then, i will access the structures without transfering them one by one from the server to the client but through the pointers declared in the client.

P.S. Thanks for ur help

If the server has created the shared memory then pass the shared memory id, passing pointer values between address spaces is wrong. With the shared memory id the clients can attach to the shared memory...

for(i = 0; i <=1000; i++)
 printf("Thank you\n");

Dude you are awesome.
You saved me A LOT of time

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.