Xuanjian Zhang
Xuanjian Zhang

Reputation: 59

How to initialize structure pointers in a structure?

typedef struct cpu{
    process_t** cpu;
    int cpu_id;
    int queue_len;
}cpu_t;

If I want to initialize this struct:

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

int i = 0;



for(i=0;i<num_processors;i++){
    cpus[i]->cpu_id = i;

    cpus[i]->queue_len = 0;
    
    cpus[i]->cpu = malloc(sizeof(process_t*)*num_process);
    
    printf("test\n");
}

The "test" will not appear and my program seems to stop after this.

Upvotes: 0

Views: 53

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

You allocated an array of uninitialized pointers

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

Thus the subscript operator returns such an uninitialized pointer as for example in this statement

cpus[i]->cpu_id = i;

and using such a pointer to access memory invokes undefined behavior.

Maybe actually you need something like the following

cpu_t *cpus = malloc( sizeof( cpu_t ) );

cpus->cpu = malloc( sizeof( process_t * ) * num_process );
//...

Pay attention to that using the same name cpu for different entities as in this structure definition

typedef struct cpu{
    process_t** cpu;
    //..

only confuses readers of the code.

Upvotes: 2

dbush
dbush

Reputation: 224387

When you do this:

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

You're allocating space for an array of pointers to cpu_t. These pointers have not been initialized, however. Then later you attempt to dereference these pointers:

cpus[i]->cpu_id = i;

Dereferencing an uninialized pointer triggers undefined behavior.

It seems that you don't actually want an array of pointers to cpu_t, but an array of cput_t. You can create such an array like this:

cpu_t *cpus = malloc(sizeof(cpu_t)*num_processors);

Then you can access each array element using . instead of ->. You'll want to make a similar change to the cpu member of cpu_t to create an array of those:

typedef struct cpu{
    process_t *cpu;
    int cpu_id;
    int queue_len;
}cpu_t;

...

for(i=0;i<num_processors;i++){
    cpus[i].cpu_id = i;
    cpus[i].queue_len = 0;
    cpus[i].cpu = malloc(sizeof(process_t)*num_process);
}

Upvotes: 1

Related Questions