Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointer becomes NULL in loop

I have found many 'pointer becomes NULL' questions, but struggling to apply the answers to my problem

I have 3 nested structs. Struct A should contain an array of struct B, which contains a single struct C which itself should contain an array of int:

typedef struct {
    int32_t *data;
    uint16_t nData;
    uint16_t dataOffset;        
} Window;

typdef struct {
    Window *window;
    const char *datasetPath;
} Dataset

typedef struct {
    char *id;
    uint8_t count;
    Dataset *datasets;
} DatasetGroup;

I have a new function for the structs:

int8_t dataset_new(Dataset *ds, const char *datasetPath, uint16_t winSize){
    ds->datasetPath = datasetPath;
    ds->window = malloc(sizeof(*(ds->window));
    ds->window->data = malloc(sizeof(int32_t) * (winSize));
    return 0;

int8_t datasetgroup_new(DatasetGroup *dg, char *id){
    dg->id = id;
    dg->count = 0;
    dg->datasets = malloc(sizeof(*(dg->datasets)) * 255);
}

And I have an add function to add a Dataset to the DatasetGroup:

int8_t datasetgroup_add(DatasetGroup *dg, const char *filePath, uint16_t winSize){
       // Create the dataset
       Dataset ds; 
       dataset_new(&ds, filePath, winSize);

       // Add the dataset to the dataset array
       dg->datasets[dg->count] = ds;
       dg->count++;
       return 0;
       }

I then iterate through the datasets in order to populate the data, doing stuff like:

     for (i = 0 ; i < datasetCount ; i++){
         Dataset *ds = &(dg->datasets[i])

Always on the 2nd interation, the data array becomes a null pointer: data = ds->window->data

I understand that I have done something wrong passing pointers around(?) but I'm not sure what precisely I have done wrong....

like image 550
jramm Avatar asked Sep 24 '26 13:09

jramm


1 Answers

This looks fine. So check another part of the code. You can debug code line by line so you can understand the segment which is creating this error.

like image 51
user29671 Avatar answered Sep 27 '26 04:09

user29671