Search code examples
cpointerssegmentation-faultrealloc

Segmentation fault after realloc(). Can't assign allocated memory to pointer


I'm trying to allocate some memory with realloc(). This works so far. But if I want to assign the allocated memory to a pointer in a struct variable, I get a segmentation fault:

// in header
typedef struct {
    int a;
    char test[20];
} MyContent;

typedef struct {
    MyContent* values; 
    // simmilar to: MyContent values[]
    // ... some other stuff
} MyData;

// in source
void myFunction(MyData* dataPtr) {
    dataPtr->values = NULL;
    MyData* tempPtr = NULL;

    for (int i = 1; i < 10; i++) {
        tempPtr = (MyContent*) realloc(dataPtr->values, i * sizeof(MyContent));
        if (tempPtr == NULL) {
            free(dataPtr->values);
            break;
        }
        dataPtr->values = tempPtr;  // Here I get the segmentation fault
        dataPtr->values[(i-1)].a = 42;
        // ...
    }
}

I can't figure out what's going wrong here. Any suggestions? Thanks for your help.


Solution

  • Seems like you edited your code. The edited code works just fine.

    #include<stdio.h>
    #include<malloc.h>
    #include<string.h>
    // in header
    typedef struct {
        int a;
        char test[20];
    } MyContent;
    
    typedef struct {
        MyContent* values; 
        // simmilar to: MyContent values[]
        // ... some other stuff
    } MyData;
    
    // in source
    void myFunction(MyData* dataPtr) {
        dataPtr->values = NULL;
        MyData* tempPtr;
    
        for (int i = 1; i < 10; i++) {
            tempPtr = (MyData*) realloc(dataPtr->values, i * sizeof(MyContent));
            if (tempPtr == NULL) {
                if(dataPtr->values)
                    free(dataPtr->values);
                printf("realloc() failed\n");
                return ;
            }
            dataPtr->values = (MyContent*)tempPtr;  // Here I get the segmentation fault
            dataPtr->values[(i-1)].a = 42+i;
            strcpy(dataPtr->values[(i-1)].test,"name");
        }
    }
    
    void PrintData(MyData* dataPtr) {
        for (int i = 1; i < 10; i++)
            printf("We have %s at %d\n",dataPtr->values[(i-1)].test,dataPtr->values[(i-1)].a);
    }
    
    main() {
        MyData Sample;
        myFunction(&Sample);
        PrintData(&Sample);
    }