user2142136 user2142136 - 1 year ago 80
C Question

Array of struct within struct (C)

I am trying to set up an array of structs within a struct in C. The size of the array is not known until runtime, so I have tried to define the array as dynamic. I have reduced my problem to the code shown below (there are a few more members in each struct, but don't pose a problem).

//struct definitions
struct intStream {
int test;

struct io {
struct inStream **inputStream;

// then proceed to main
int numDevices = 4; //(derived from number of devices found at runtime)
struct io *devices;
devices->inputStream = malloc(sizeof(struct inStream) * numDevices)

// Fails on
devices->inputStream[0]->test = 1;

I am still relatively new to C style programming, so my understanding of memory is not complete, but through some searching I have not been able to find alternate solutions to my problem besides the struct hack which aesthetically I do not like, as well as wanting the option to include more arrays in future.

Answer Source

In this code, devices is uninitialized. Using uninitialized memory invokes undefined behavior.

You need to make devices point to some valid memory before you can dererefence that pointer.

That said,

 devices->inputStream = malloc(sizeof(struct inStream) * numDevices)

also looks wrong. What you may want is

 devices->inputStream = malloc(sizeof(struct inStream *) * numDevices);

and then, you need to allocate memory to each devices->inputStream[i], also.

[Modified code by OP, removed from question and added into the answer, just for reference]

struct io *devices;
devices = malloc(sizeof(*devices));  

devices->inputStream = malloc(sizeof(struct inStream *) * numDevices);

for(int i = 0; i < 4; i++) {  
    devices->inputStream[i] = malloc(sizeof(struct inStream));  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download