views:

226

answers:

3

I have the STRUCT1 Structure declared as below

typedef struct struct1 {
    short int nbr_fe;
    [size_is(nbr_fe)] STRUCT2  ptr_fe[*];
} STRUCT1;

STRUCT2 is also another structure inside STRUCT1

and then I have a pointer declared to it as below

typedef [ptr] STRUCT1 * ptr;

And I have to allocate a memory to an array of STRUCT1 base on the nbrRequested And so far I have

STRUCT1 obj1;
memset((void*)&obj1, '\0' , sizeof(STRUCT1));

for(int i1=0;i1<(int)nbrRequested;i1++) {
   STRUCT2 obj2;
   memset((void*)&obj2, '\0' , sizeof(STRUCT2));
   obj1.ptr_fe[i1] = obj2;
}

ptr ptr2;
ptr2 = &obj1;

but if the nbrRequested is greater than 500, the loop goes in infinite and the application hangs.

Is there any better way to allocate a memory without using for loop

+3  A: 

This snippet should clear up that you need to malloc the memory, clear it, then you can assign the pointer to the structure member.

STRUCT1 listWU;
memset(&listWU, 0 , sizeof(STRUCT1));
for(int i1=0; i1<(int)nbrRequested; i1++) {
    STRUCT2 *temp;
    temp = malloc(sizeoF(STRUCT2));
    memset(temp, 0 , sizeof(STRUCT2));
    listWU.lst_Workunit_fe[i1] = temp;
}

Oh, and don't forget when you're done with this structure, you need to free up all the pointers that were malloc'd in this structure or you'll have a memory leak.

spoulson
Sorry I have formatted the structure declarations for better readability
ronan
+2  A: 

You're not allocating anything, you're overwriting the same data on the stack (which then goes out of scope when the loop exits.

In C++, you allocate memory with the new operator. In C you'd use malloc. So a minimal rewrite of your code would be something like this (in C, since that seems to be what you're writing)

// Allocate enough space for the array of `WF_LIST_WORKUNIT_P_FE`s
WF_LIST_WORKUNIT_P_FE listWU = malloc(sizeof(WF_STRUCT_WORKUNIT_FE) * nbrRequested);
memset(listWU, 0, sizeof(WF_STRUCT_WORKUNIT_FE) * nbrRequested));

Of course, this just sets every struct in the array to 0, rather than a more meaningful initialization, if that is what you want.

jalf
A: 

Since this is a C++ code

I would use new operator as below

WF_LIST_WORKUNIT_P_FE *listWU = new WF_STRUCT_WORKUNIT_FE [nbrRequested + 1];

The catch is structure WF_STRUCT_WORKUNIT_FE itself is a nested structure of Structure WF_LIST_WORKUNIT_FE that is typedef struct wf_list_workunit_fe
{ short int nbr_Workunits_fe; [size_is(nbr_Workunits_fe)] WF_STRUCT_WORKUNIT_FE lst_Workunit_fe[*]; } WF_LIST_WORKUNIT_FE;

wouldnt allocating a memory to WF_LIST_WORKUNIT_FE work ?

ronan