Search code examples
cstructinitialization

initializing a struct that contains a struct pointer to another struct


So I apologize in advance for maybe not being able to articulate this very well. I am quite new to this and am learning as I go along. I am looking to initialize a struct that has a struct pointer to another struct inside of it. Check below.

struct GraphicElement {
    char* fileName;
    struct GraphicElement* pNext;
    };
struct RasterGraphic {
    struct GraphicElement* GraphicElements;
};

I am writing functions to add or delete graphic elements but before that I make a call to a function where I would like to do the initialization which is where I am having trouble.

int main(void)
{
    char response;
    BOOL RUNNING = TRUE;
    struct RasterGraphic RG;
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    InitRasterGraphic(&RG);
}

I make the call to init here and below will be my attempt.

void InitRasterGraphic(struct RasterGraphic* pA)
{

pA->GraphicElements = malloc(sizeof(struct GraphicElement));
pA->GraphicElements = 0;
return; 
}

I have tried many other things but none seem to work with that I want to do. I want to initialize everything. I have another function that prints the elements but it crashes and I get an error that It cannot read the memory where fileName and pNext are. Again this is the first time I post a question on here. I am hoping ive covered all my bases and that ive asked it properly. Thank you.


Solution

  • You are initializing pA->GraphicElements to NULL immediately after mallocing it is wrong and it leads to memory leak.

    May be you wanted to try as below.

    void InitRasterGraphic(struct RasterGraphic* pA)
    {
       pA->GraphicElements = malloc(sizeof(struct GraphicElement));
    
       if (pA->GraphicElements == NULL) return;
    
       pA->GraphicElements->pNext = NULL;
       pA->GraphicElements->fileName = NULL;
    
       /** or
        pA->GraphicElements->fileName = malloc(sizeof(char)*(somelength));
        */
    
       return; 
    }