Thread: When and when not to use malloc()?

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    55

    Question When and when not to use malloc()?

    Hey all,

    I'm getting myself in a bit of a mess I think. Let's say you've set up 2 pointers to structs, for a linked list. You've initialised them both to NULL, as in the following code fragment:

    Code:
    typedef struct something {
      int key;
      struct something *next;
    } somestuff;
    
    somestuff *topnode = NULL, *currentnode = NULL;
    
    int main(void) {
      ...
    }
    My question is, is it advisable to make a call to malloc() to use topnode and currentnode? I usually end up adding nodes with something like:

    Code:
    currentnode = topnode;
    
    if (topnode == NULL)
      topnode = newnode;
    else
    {
      for (currentnode = topnode; currentnode->next != NULL; currentnode = currentnode->next)
        ;
      currentnode->next = newnode;
    }
    Just getting a bit confused as to when to use it. Could do with a simple explanation (or link to one if possible. I've looked but Google is coming up with some weird links to parsing with malloc()).

    Be very grateful for any help you can provide me.

    --John.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's pretty simple, when you need something dynamicly allocated, call malloc. Otherwise, don't. :P

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    55
    Thanks for the reply mate. Judging from your reply, I think my question is probably incorrect then. I don't actually know when to dynamically allocate memory. I can think of some obvious instances, like with a pointer to an array of strings, whose lengths differ, but when it comes to something like nodes of a linked-list, I have absolutely no idea if I should be calling malloc() or not.

    Again, thanks for the reply.

    --John.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    In a linked list, you want to make a new node whenever you need to add something to the list. Here is a quick example:
    Code:
    struct node * newNode( const char * s )
    {
        struct node * nn = NULL;
    
        nn = malloc( sizeof( struct node ) );
        if( nn == NULL )
        {
            printf("Malloc failure. You're toast.\n");
            exit( 0 );
        }
        strncpy( nn->name, s, NAME_SIZE );
        return nn;
    }
    Here I assume we have an array in our node called 'name', whose size is 'NAME_SIZE' bytes. In this example, I pass an argument to the node creation function to assign a name to our node as we make it.

    Free the node when you're done with it.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Dec 2001
    Posts
    44
    There's a simple way you can tell whether or not you should be using malloc.

    There are only two ways you can have memory allocated: either through malloc and friends, or by declaring a variable. Memory allocated with malloc exists until you free it. Automatic variables (which is what you get when you normally declare a variable) exist only within the scope in which they were declared. Once that scope ends, the variable no longer exists. (This doesn't include static variables which do something else, but I digress...)

    So, the question to ask is whether or not you want the memory you've allocated to live only within a restricted scope, or whether it should be allocated until you free it.

    If, for example, you want to return the allocated memory, or add it to some data structure, then you probably want the memory to exist long after the scope (block or function) in which you're using it. In that case, you want to use malloc or one of it's friends.

    If, on the other hand, your variable only needs to exist inside this block or function then you can use an automatic variable. Here you could, if you wished, use malloc and friends. Most of the time you don't need to and you can just use an automatic variable. The times when you'd want to use malloc over an automatic variable would be when you need to resize the allocated memory (an expanding list of strings for example) or when you want a more complex data structure and it's easier to use malloc than automatic variables (a struct which has a pointer to a string: you could assign it the pointer to an automatic variable, but it's probably easier to manage if you just allocate the amount of memory you need and store the pointer to it in the struct.)

    If that makes any kind of sense, then you're probably not a newbie... but hopefully it explains a little about when and where to use malloc and friends.

    Ian Woods

  6. #6
    Registered User
    Join Date
    Aug 2002
    Posts
    55
    Ah, I see. So, you'd allocate the memory for the new node because obviously you don't know the size of it (plus the pointer needs some space allocated for the struct's contents anyway). So I think that should mean that in my example of *topnode and *currentnode, you wouldn't need to allocate memory for them, because you are making them point at certain memory locations that already have space allocated (if that makes sense).

    Think I've got it. Thanks dude.

    Edit: Thanks guys even. lol.

    --John.
    Last edited by John.H; 03-24-2003 at 06:05 PM.

Popular pages Recent additions subscribe to a feed