Domanda

Ho la struttura struct1 dichiarata come di seguito

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

STRUCT2 anche un'altra struttura interna struct1

e poi ho un puntatore dichiarato come qui sotto

typedef [ptr] STRUCT1 * ptr;

E devo allocare una memoria per una matrice di base di struct1 sul nbrRequested E finora non ho

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;

, ma se il nbrRequested è superiore a 500, il ciclo va in blocco infinite e l'applicazione.

C'è un modo migliore per allocare una memoria senza utilizzare per il ciclo

È stato utile?

Soluzione

Non stai assegnando nulla, si sta sovrascrivendo gli stessi dati nello stack (che poi va fuori del campo di applicazione quando l'uscita dal ciclo.

In C ++, è allocare memoria con l'operatore new. In C usereste malloc. Quindi, una riscrittura minima del codice sarebbe qualcosa di simile (in C, dal momento che sembra essere quello che stai scrivendo)

// 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));

Naturalmente, questa imposta solo ogni struct nella matrice a 0, piuttosto che una di inizializzazione più significativo, se questo è ciò che si desidera.

Altri suggerimenti

Questo frammento dovrebbe chiarire che è necessario malloc la memoria, chiaro, allora si può assegnare il puntatore per il membro della struttura.

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, e non dimenticare quando hai finito con questa struttura, è necessario liberare tutti i puntatori che sono stati malloc'd in questa struttura o avrete una perdita di memoria.

Dal momento che questo è un codice C ++

Vorrei usare operatore new, come di seguito

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

Il problema è la struttura WF_STRUCT_WORKUNIT_FE sé è una struttura annidata di Struttura WF_LIST_WORKUNIT_FE questo è  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 l'assegnazione di una memoria di lavoro WF_LIST_WORKUNIT_FE?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top