Thread: Memory leak issues! Please help! >_<

  1. #16
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > countryList[i] = (char*) calloc (strlen(tempAry), sizeof(char));
    1. Don't cast the result of malloc/calloc etc - see the FAQ for why.
    2. You don't count the \0, so the strcpy which follows is instant buffer overflow.

    > countryList[i] = (char*) calloc (strlen(tempAry), sizeof(char));
    > countryList[numCountries] = '\0';
    When you exit the loop, i == numCountries, so this is just a memory leak.
    '\0' silently becomes NULL with this assignment.

    Edit:
    Bah, way way too late - the party is over.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  2. #17
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by RaDeuX View Post
    I didn't know '/n' counted as a character as well, which was part of the reason why I didn't have that extra character space. Thanks for your input, there are no more memory leaks now.
    It does, but strlen counts that so that's fine. What strlen doesn't count is the \0 that gets written on as well.

  3. #18
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by RaDeuX View Post
    No I don't. i is 13 after the for loop ends.
    Excuse me!!
    Copying a NULL terminated string requires allocating length for the nul char at the end as well. The code needs to be:
    Code:
    countryList[i] = calloc(strlen(tempAry)+1, sizeof(char));
    Note the required +1.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory leak with detached pthreads - how to free?
    By rfk in forum Linux Programming
    Replies: 2
    Last Post: 08-17-2007, 06:50 AM
  2. Replies: 2
    Last Post: 09-28-2006, 01:06 PM
  3. How to detect a memory leak?
    By g4j31a5 in forum C++ Programming
    Replies: 11
    Last Post: 07-19-2006, 11:35 AM
  4. Memory Leak?
    By BigDaddyDrew in forum C++ Programming
    Replies: 11
    Last Post: 12-09-2002, 04:28 PM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 01:41 PM