0

I'm trying to use an array of iNodes (structure I made):

 typedef struct iNode
{
    int id;
    int size;
    int pointers[NUM_POINTERS];
} iNode;

I get segmentation fault in this code:

for (int k = 0; k < NUM_POINTERS-1; k++) {
            root->pointers[k+1] = k+2;
            iNode *inodes[maxiNodePerBlock];


            for (int i = 0 ; i<maxiNodePerBlock; i++) {
                iNode *tmp = malloc(sizeof(iNode));
                tmp->id = -1;
                tmp->size = -1;
                for (int j= 0; j< NUM_POINTERS; j++) {
                    tmp->pointers[j] = -1;
                }
                strcpy(inodes[i], tmp);
                free(tmp);
            }
            write_blocks(k+1, 1, inodes);
        }

on the strcpy(inodes[i], tmp); line. So I tried to initialize it :

iNode *inodes[maxiNodePerBlock] = malloc(sizeof(iNode)*maxiNodePerBlock);

but then I get the error: variable-sized object may not be initialized

Any suggestions?

Nicky Mirfallah
  • 1,004
  • 4
  • 16
  • 38

1 Answers1

1
 strcpy(inodes[i], tmp);

When you reach the above line, No memory is allocated for inodes[i]. You can directly allcoate memory for inodes[i] instead of using tmp

for (int i = 0 ; i<maxiNodePerBlock; i++) {
            inodes[i] = malloc(sizeof(iNode));
            inodes[i]->id = -1;
            inodes[i]->size = -1;
            for (int j= 0; j< NUM_POINTERS; j++) {
                inodes[i]->pointers[j] = -1;
            }
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34