Thread: malloc and realloc

  1. #1
    Registered User
    Join Date
    Apr 2005

    malloc and realloc

    char *str;
    str = (char *) malloc (sizeof (char) * strlen("hello"));
    strcpy(str, "hello");
    str = (char *) malloc (sizeof (char) * strlen("bye bye"));
    strcpy(str, "bye bye");
    is the above code memory OK or the continuous allocation of malloc will lead to a memory leak problem (imagine i have a big loop of reading strings)? in other words is the use of malloc correct or do i need to use realloc? as i think the only difference between the two is that malloc is destructive without copying the previous contents while realloc is also destructive but copies the old contents if necessary

    Last edited by odysseus.lost; 05-27-2005 at 04:25 AM. Reason: clarification

  2. #2
    Join Date
    May 2005
    You have a buffer overflow in your code by the way. It should read
    str = (char *) malloc (sizeof (char) * (strlen("hello")+1));
    instead of
    str = (char *) malloc (sizeof (char) * strlen("hello"));
    It's because strlen does not count the leading '\0' character, so you're not allocating space for it. If you try to printf str later, you'll continue to print garbage until a NUL character is encountered in memory.

  3. #3
    Registered User
    Join Date
    Jan 2005
    As for your question, you do have a memory leak. Either free the memory pointed to by str before mallocing more memory or use realloc.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Oh, and stop typecasting malloc. As with all functions that return void pointers, you don't ever typecast their return values. There's information on the FAQ as why not to do this. If it gives you a warning when you don't typecast, then stop compling as C++ and compile as C.

    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, realloc..wat on earth!
    By zesty in forum C Programming
    Replies: 3
    Last Post: 12-21-2007, 01:42 PM
  2. To malloc or not realloc on struct members
    By gh0st in forum C Programming
    Replies: 4
    Last Post: 11-17-2006, 05:27 AM
  3. malloc, realloc
    By figo2476 in forum C Programming
    Replies: 3
    Last Post: 04-28-2006, 10:11 PM
  4. Linked list versus malloc and realloc.
    By Bajanine in forum C Programming
    Replies: 2
    Last Post: 06-20-2005, 08:08 PM
  5. Need help on malloc and realloc
    By YevGenius in forum C Programming
    Replies: 8
    Last Post: 03-06-2004, 01:55 AM