Search code examples
csegmentation-faultdynamic-memory-allocation

Creating arrays within structs? Segmentation fault


I compiled this small amount of C code and when I run it, I get a segmentation fault.

It stops in the first lines of the create_index() function even though I have permission to access the addresses of the pointers. I have no clue what's going on.

main.c

 #include <stdio.h>
 #include "hash.h"

int main(void)
{       HTinfo *head;
        create_index(&head);
        return 0;
}

hash.c

 #include <stdio.h>
 #include <stdlib.h>
 #include "hash.h"

int create_index(HTinfo **head)
{       int i;
        (*head)->empty = 1;
        (*head)->index = malloc(101*sizeof(nodeptr));
        if ((*head)->index == NULL)
            return -1;
        for (i=0; i < 101; i++)
            (*head)->index[i] = NULL;
        return 0;
}

hash.h

typedef struct rc *nodeptr;

typedef struct rc {
    char ln[25];
    char fn[15];
    char city[25];
    char prefecture[3];
    int debt;
    int afm;
    nodeptr next;
} record;

typedef struct ht {
        nodeptr *index;
        char empty;
} HTinfo;

Solution

  • You didn't allocate memory for head. Either malloc in main:

    HTinfo * head = malloc(sizeof *head);
    if(NULL == head) // handle out-of-memory
    

    or in create_index:

    *head = malloc(sizeof **head);
    if(NULL == *head) // handle out-of-memory