Thread: malloc doubt

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    146

    malloc doubt

    what will happen if I have a piece of code like this

    buffer = malloc(some_amount);
    ........
    ........

    buffer = malloc(some_amount);


    I don't have a free statement in between, when a second malloc is used what happens to the first allocation?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by edesign
    I don't have a free statement in between, when a second malloc is used what happens to the first allocation?
    Nothing. If buffer was the only pointer to the memory previously allocated, you would then be unable to avoid a memory leak.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It is leaked. No doubt about that.

    You should call free with the original value before you call malloc again.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Feb 2008
    Posts
    146
    I also thought that it must be causing a leak, but was not so sure....

    Thanks...
    Edesign

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by edesign
    I also thought that it must be causing a leak, but was not so sure....
    If you want to be sure, post also the code that you did not show. For example, this does not result in a memory leak despite having the pattern of what you showed us:
    Code:
    char *buffer;
    char *buffer2;
    buffer = malloc(some_amount);
    buffer2 = buffer;
    buffer = malloc(some_amount);
    free(buffer);
    free(buffer2);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Feb 2008
    Posts
    146
    ya, now buffer2 is pointing to the location buffer1 used to. So I'll be able to free both the buffers (allocated memory) and that will no longer cause a memory leak.

    and i don't have any code, i was just thinking about such a situation that's why posted just pseudo-code type of thing, otherwise I wouldn't hasitate to post the code ...

    Thanks
    Edesign

  7. #7
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    I wouldn't classify it necessarily as a "leak" situation unless it's in a loop and the number such inaccessible chunks of memory keep growing. Or it may still not be a leak if the programmer intended on counting the number of times a certain sized chunk of memory can be cumulatively allocated before the malloc failed... The returned pointer would need to be checked for NULL of course to sanely stop the program at some point.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It is always a leak if the memory is not freed correctly - it may be an INTENTIONAL leak or a unintentional leak, but it's a leak all the same.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    I stand corrected on the definition of 'leak'. To me the word leak implies an unintended program bug. Your definition includes any malloc which does not have a corresponding free before the termination of the program (which frees memory anyhow making the bug moot).

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Leaving intentional leaks in the code sucks. When somebody picks up your code months or years later, and runs it through a memory analyzer, this leak will appear, and that person will then waste their time determining where the bug is, ultimately discovering that it was intentional in the first place.

    Even Microsoft's own libraries do this sometime. It makes it extremely difficult to write automated leak testing scripts, because you have to account for the leaks which are considered "ok," and these can change between releases of the libraries. So instead of the simple condition if num_leaks == 0: test_pass() you have some monstrosity which parses the results and figures out whether things are okay or not.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by nonoob View Post
    I stand corrected on the definition of 'leak'. To me the word leak implies an unintended program bug. Your definition includes any malloc which does not have a corresponding free before the termination of the program (which frees memory anyhow making the bug moot).
    I would define "leaked" as any memory to which you no longer have access, because you lost the pointer. That is straight forward and unambiguous.

    I would agree that as long as you still have access via a pointer, the memory is *not* leaked even if you do not free() it before termination. It may, however, be wasteful of resources. But there are other ways to do that, eg
    Code:
    char line[24000000];
    printf("Enter your name: ");
    fgets...line
    which would not be called a leak.

    Valgrind I believe calls anything not freed() lost memory, which makes valgrind very dumbass in my book. As brewbuck hints at, there are numerous very widely used libraries which do not pointlessly free() memory "at exit" rendering valgrind useless for mem profiling applications which use those libraries.
    Last edited by MK27; 06-04-2009 at 07:36 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    But Valgrind makes a distinction between "lost" and "existent" pointers.

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by nonoob View Post
    Your definition includes any malloc which does not have a corresponding free before the termination of the program (which frees memory anyhow making the bug moot).
    Would you really want to use a program where the programmer tells you "You must terminate the program to stop it running out of memory resources"?

    Not all operating systems seek to release memory, or other resources, used by a program as the program exits. Even in modern operating systems that do seek to release memory as a program exits, relying on that is one way to encounter obscure bugs in operating systems, and have those appear as vexing problem reports with your program.

    Memory leaks are also a critical concern in long-running programs i.e. those which are required to run 24/7 and cannot be simply terminated and restarted. In such programs, memory leaks tend to show up in obscure manners such as unexplained slowdowns, lockups, or abnormal terminations.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by grumpy View Post
    Would you really want to use a program where the programmer tells you "You must terminate the program to stop it running out of memory resources"?
    So what was the other option -- a program where the programmer assures you "Oh, this program does not use any resources while it is running." What you are saying does not make sense. Did you free() argv[0]? A running program uses memory. It will do so until terminated, unless you think writing a program that continues, doing nothing with nothing, is normative.

    Not all operating systems seek to release memory, or other resources, used by a program as the program exits.
    I am pretty sure you are wrong about that, because try as I might, I doubt I could write anything that would consume say, 200 MB, and then I terminate the process and re-run it until I am out of memory? No. I run the process, it takes 200 MB. I terminate the process, it takes 0 Mb. End of story. I could sit here all day trying, as long as I only have one instance, I won't consume more than 200 MB. Terminated processes release their memory.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by MK27 View Post
    So what was the other option -- a program where the programmer assures you "Oh, this program does not use any resources while it is running." What you are saying does not make sense. Did you free() argv[0]? A running program uses memory. It will do so until terminated, unless you think writing a program that continues, doing nothing with nothing, is normative.
    You missed his point. His point was that a program shouldn't be required to shut down to stop memory leaks, and he cited practical examples of programs that are required to run quite for long periods of time. He wasn't talking about using no resources, but simply running out of resources.... ie. leaking memory.

    Whoever allocates should deallocate. argv is allocated by the underlying implementation, not your program, so your parallel is rather.... unfitting.

    Quote Originally Posted by MK27 View Post
    I am pretty sure you are wrong about that, because try as I might, I doubt I could write anything that would consume say, 200 MB, and then I terminate the process and re-run it until I am out of memory? No. I run the process, it takes 200 MB. I terminate the process, it takes 0 Mb. End of story. I could sit here all day trying, as long as I only have one instance, I won't consume more than 200 MB. Terminated processes release their memory.
    I believe it was Windows 98 that was discussed here some time ago that was discovered, at one point, to have a bug that lost malloc()ed memory that wasn't properly free()ed by the programmer, but I could be wrong on the details.

    Modern operating systems are generally pretty good about details in subjects like these, at least better than operating systems used to be, but you can't always be sure what actually happens in an unknown OS when talking about C. His point was that if having a memory leak is potentially going to break an OS, don't do it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM