views:

514

answers:

3

I have a struct with a dynamic array inside of it:

struct mystruct{
 int count;
 int *arr;
}mystruct_t;

and I want to pass this struct down a pipe in C and around a ring of processes. When I alter the value of count in each process, it is changed correctly. My problem is with the dynamic array.

I am allocating the array as such:

mystruct_t x;
x.arr = malloc( howManyItemsDoINeedToStore * sizeof( int ) );

Each process should read from the pipe, do something to that array, and then write it to another pipe. The ring is set up correctly; there's no problem there. My problem is that all of the processes, except the first one, are not getting a correct copy of the array. I initialize all of the values to, say, 10 in the first process; however, they all show up as 0 in the subsequent ones.

for( j = 0; j < howManyItemsDoINeedToStore; j++ ){ x.arr[j] = 10; }

Initally:       10      10      10      10      10
After Proc 1:   9       10      10      10      15
After Proc 2:   0       0       0       0       0
After Proc 3:   0       0       0       0       0
After Proc 4:   0       0       0       0       0
After Proc 5:   0       0       0       0       0
After Proc 1:   9       10      10      10      15
After Proc 2:   0       0       0       0       0
After Proc 3:   0       0       0       0       0
After Proc 4:   0       0       0       0       0
After Proc 5:   0       0       0       0       0

Now, if I alter my code to, say,

struct mystruct{
 int count;
 int arr[10];
}mystruct_t;

everything is passed correctly down the pipe, no problem. I am using READ and WRITE, in C:

write( STDOUT_FILENO, &x, sizeof( mystruct_t ) );
read( STDIN_FILENO, &x, sizeof( mystruct_t ) );

Any help would be appreciated. Thanks in advance!

+1  A: 

You're only writing the struct. If you want to pass the array of integers around, you'll have to write that to the pipe, too. This is why your second option is working, as the array is specified as part of the struct.

CWF
A: 

In the dynamic case, your struct does not contain the array itself, merely a pointer to it. (If you check sizeof( mystruct_t), you can see that it's only big enough to contain an int and a pointer).

You cannot (meaningfully) write a pointer from one process to another.

If you want to copy a variable-sized array, you'll have to do 2 write operations: the first one will write mystruct.count, the second one will write the array of ints.

David Gelhar
A: 

Hello,

When you alloc your dynamic array malloc function gives back a pointer to a memory space which is not in your struct. Take a look at the example:

0x0000000F int count
0x00000014 >> pointer to your array elsewhere 0x000000F0


0x000000F0 your array is here

You could pad your struct with well known datas to demonstrate it.

struct mystruct{
  int count;
  int *arr;
  char pad [5];
}mystruct_t;
mystruct_t x;
x.pad={0x5b,0x5C,0x5D,0x5E,0x5F};