1

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.

1
  • 3
    You first assign pA->GraphicElements = malloc(...) and then immediately do pA->GraphicElements = 0. Think about that for a little while. In my opinion one of those is almost correct (and it's not any allocation). Commented Sep 22, 2018 at 14:20

1 Answer 1

1

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; 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.