Thread: Here we go again: when to use Malloc and when not?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    99

    Here we go again: when to use Malloc and when not?

    I do not have a good theoretical grasp of when to use malloc(). I know what it does, but I am too new to C to really dig it. I am quite aware that a considerable number of eyes are starting to glaze over now out of sheer boredom, but I searched for it, found a lot, but nowhere a good and concise overview.

    I have found one clear use for malloc(), if I want persistent results from a function that do not get cleared when I exit the function, I use malloc. The rest is kind of vague with ominous talks about memory management, safe pieces of memory and what all, conceptual clarity is lacking. So, to be clear, my question is when one should use malloc.

    The example I am using is a very simple concatenation.

    Malloc version (not mine):
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define BEGIN "@@"
    #define END "CCC"
    
    int main (void)
      {  
        char *result = malloc(100 * sizeof(char));  // create some string space
    
        strcpy(result, BEGIN);              
        // result holds @@
        strcat(result, "this is a message");
        //result holds @@this is a message
        strcat(result, END);   
        // result holds @@this is a messageCCC
    
        printf("%s\n\n", result);
        free(result); 
        return 0; }
    The version without malloc:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define BEGIN "@@"
    #define END "CCC"
    
    int main (void)
      {  
       char *result;
    
        strcat(result, BEGIN);    
        // result holds @@
        strcat(result, "this is a message");     
        //  result holds @@this is a message
        strcat(result, END);   
        // result holds @@this is a messageCCC
    
        printf("%s\n\n", result);
        return 0; }
    Both versions run well, but is this coincidence? What risks to I run if I work without malloc in this case, is this good programming or a don't?
    Last edited by django; 08-08-2011 at 08:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  2. Malloc help
    By MyNameIs.. in forum C Programming
    Replies: 5
    Last Post: 04-19-2010, 02:19 PM
  3. Replies: 7
    Last Post: 10-01-2008, 07:45 PM
  4. malloc()
    By vb.bajpai in forum C Programming
    Replies: 8
    Last Post: 06-14-2007, 10:50 AM
  5. When and when not to use malloc()?
    By John.H in forum C Programming
    Replies: 5
    Last Post: 03-24-2003, 06:00 PM