Search code examples
cpointersstructdynamic-memory-allocation

segmentation fault during the use of an array of pointer to structures


I have to save in an array the address of some data. Every data is a structure of type "dagNode". To do my work I visit a list, and I count the number of data that I want to record its address so I allocate the right space in the memory, and finally I re-visit the list and save the address of some data.

    struct dagNode *buildBST(struct dagNode *rootList){
    struct dagNode *head, **xTest;
    head = rootList;
    int numXtest=0;

    rootList = nextNode(TYPE_XTEST, rootList);

    while ( !IS_TERMINATED( rootList ) ){   // first visit
        numXtest++;
        rootList = nextNode(TYPE_XTEST, rootList); }

    xTest = (struct dagNode **) malloc( sizeof(struct dagNode ) * numXtest);
    int i=0; rootList = nextNode(TYPE_XTEST, head);

    for(i=0; i<numXtest; i++){      // second visit, saving the address of some datas
        rootList = nextNode(TYPE_XTEST, rootList);
        xTest[i] = rootList; i++;
    >>> printf("t=%d,val=%d\t", xTest[i]->nodeType, xTest[i]->val); } // segmentation fault

    return head;
    }

EDIT:

    struct dagNode *nextNode(int typeOfNextNode, struct dagNode *node){
        if (IS_TERMINATED(node)){   return node;    }
        node = node->next;
        if (typeOfNextNode == TYPE_EDGE_OR_GAP){
            while (!IS_TERMINATED(node) && !IS_AN_EDGE(node) && !IS_A_GAP(node)){
                node = node->next;  }
               }else
        {
            while (!IS_TERMINATED(node) && (node->nodeType != typeOfNextNode)){
                node = node->next;}
        }
        return node;    }

Solution

  • There is a mismatch between the type of the xTest pointer and the size you allocate in malloc. If xTest is of type struct dagNode **, the proper allocation should be:

    xTest = malloc(sizeof(struct dagNode *) * numXtest);
    

    Probably you want to allocate numXtest pointers to a struct, not numXtest structs.