1

I have a "Server" and a "Client" process, they "communicate" through a struct shared memory.

typedef struct
{
  char* buffer;
  int cards;
  int maxCards;
}  myStruct

Both "Server" and "Client" processes can get/set the values of the two int types, but the thing is different with the buffer (we use this as a pointer to chars): the "Server" allocates memory, like:

(*sharedMem).buffer = (char*) malloc(sizeof(char)*maxCards);

has the ability to set or get values:

(*sharedMem).buffer[0] = 'a';
printf("%c\n",(*sharedMem).buffer[0]);

but when the "Client" process tries to access a char:

printf("%c\n",(*sharedMem).buffer[0])

It collapses with Segmentation Fault Core Dumped error. Is there a way to solve this problem without using an Array or List? Any Ideas?

MEZesUBI
  • 297
  • 7
  • 17
  • 2
    Both processes have different address spaces, so pointers in one may be meaningless in the other? – Jens Dec 24 '15 at 11:07
  • Why can't you use an array or a list? Because using an array for the buffer is exactly the solution you need. – fuz Dec 24 '15 at 11:16
  • @Jens is there any way I can send the pointed adresses to the "Client" process? – MEZesUBI Dec 24 '15 at 11:24
  • @FUZxxl That is a solution and if I cannot change adresses between the processes, I'll use a list. – MEZesUBI Dec 24 '15 at 11:24
  • 1
    Found the answer, this question was already answered: http://stackoverflow.com/questions/14558443/c-shared-memory-dynamic-array-inside-shared-struct – MEZesUBI Dec 24 '15 at 11:28
  • @MEZesUBI Not really. Instead of pointers, you can use “message numbers” or something like that and then send over a set of messages. Generally, try to avoid using pointers when sending data over the nentwork. But why did you exclude arrays in your question? – fuz Dec 24 '15 at 11:28

1 Answers1

2

Both processes have different address spaces, so pointers in one are generally meaningless in the other (except for possibly NULL).

If you need to exchange more data between processes, you could use

  • pipes (see the pipe() system call)
  • shared memory (see POSIX shm* calls)
  • memory mapped files (see mmap())
  • use an array-of-char in your struct
Jens
  • 69,818
  • 15
  • 125
  • 179