Question

I am having a structure that includes a set of other structures:

 typedef struct{
    int cell_Type;      //user association: 0--> Macro 1--> Femto
    int cell_ID;        //cell ID that the user is associated with
}association;

 //User struct
 typedef struct{
    coord c;                //coordinates
    association id;             //association parameters
    capacity cap;               //capacity parameters   
 }usu;

 //Struct with a vector of users
 typedef struct{
     usu user[NUM_USERS+NUM_HS]; //each user is defined by the association (id), etc...
 }vectusers;

void main(int argc,char *argv[])
{
       //.....

       //memory allocation for the structures
       users_ptr=calloc(1,sizeof(vectusers)); //users pointer

       //.....
}

So far so good, up to this point that there has been the need for an array that I will not know its size until the program is almost finished.

As such, the structure will be:

 typedef struct{
    int cell_Type;      //user association: 0--> Macro 1--> Femto
    int cell_ID;        //cell ID that the user is associated with
    int assigned_RBs;   //counter of how many resources have been assigned
    int *RB_number;     //array with size according to assigned_RBs counter
}association;

My problem is with the malloc() and realloc(). Actually I think I am reserving correctly memory with the malloc:

users_ptr->user[u].id.RB_number = malloc(1*sizeof(int));

but when it comes to realloc(), I do not change the size of the array:

users_ptr->user[index_max_W].id.assigned_RBs++;

size = users_ptr->user[index_max_W].id.assigned_RBs;

users_ptr->user[index_max_W].id.RB_number = realloc((users_ptr->user[index_max_W].id.RB_number),size);

where index_max_w is the index of the user with a max value of a statistic. Both size and index_max_W have been declared as int.

Could someone please help me with the realoc in this case?

Was it helpful?

Solution

The size argument to realloc() is in bytes, just like the argument to malloc(). Your code seems to omit tihs scaling for the realloc(), which will lead to (drastic) under-allocation and thus undefined behavior if you access the memory.

It should be something like:

const size_t new_size = users_ptr->user[index_max_W].id.assigned_RBs;

users_ptr->user[index_max_W].id.RB_number = realloc(users_ptr->user[index_max_W].id.RB_number,
new_size * sizeof *users_ptr->user[index_max_W].id.RB_number);

It's a bit unwieldy due to the nested name of the target pointer. We can simplify that by using a suitable temporary pointer variable to remove the repeated complicated access:

usu *user = &users_ptr->user[index_max_W];
user->id.assigned_RBs++;
user->id.RB_number = realloc(user->id.RB_number,
                             user->id.assigned_RBs * sizeof *user->id.RB_number);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top