Thread: Structs and mem allocation

  1. #1
    Registered User
    Join Date
    Mar 2007

    Structs and mem allocation

    Hi all,

    I have a struct which contains not only basic data but other structs as well, some of which are large, I allocate my main struct the normal way and free it but I notice that it will crash on the free when I have too many larger structs within my main struct that I allocated mem for, it looks like this:

    struct mainStruct {
    int blah1;
    int blah2;
    bigStruct data1;
    bigStruct data2;
    bigStruct data3;
    mainStruct myStruct = malloc(sizeof(mainStruct));
    free(myStruct); // crash
    is the correct practice to declare 'bigStruct' as a pointer and allocate mem for it, I've tried this and there is no problem but now i'm wondering about all the other places where I have structs within structs(most are pretty light) but what is the right thing to do here?

    Thanks in advance...

  2. #2
    The larch
    Join Date
    May 2006
    Yes, myStruct should be a pointer. If you allocate memory you get a pointer to the memory, not the struct instance itself. (And you can free only pointers.)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Cape Town
    I haven't touched C in a long time, but memory allocation isn't mandatory for structs. They are treated as normal variables and placed on the stack...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Allocation and Structs
    By reversaflex in forum C Programming
    Replies: 7
    Last Post: 04-04-2008, 02:46 PM
  2. Relate memory allocation in struct->variable
    By Niara in forum C Programming
    Replies: 4
    Last Post: 03-23-2007, 03:06 PM
  3. Problem with array of structs
    By Wiretron in forum C Programming
    Replies: 3
    Last Post: 09-03-2006, 02:07 PM