Dynamically allocated memory question

This is a discussion on Dynamically allocated memory question within the C Programming forums, part of the General Programming Boards category; Consider this: Code: int i; char *v[MAXELEMENTS]; for (i = 0; i < MAXELEMENTS; i++) { if ((v[i] = malloc(blablabla)) ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    Dynamically allocated memory question

    Consider this:
    Code:
    int i;
    char *v[MAXELEMENTS];
    
    for (i = 0; i < MAXELEMENTS; i++) {
        if ((v[i] = malloc(blablabla)) == NULL) {
            printf("error\n");
            while (--i >= 0)
                free(v[i]);
            break;
        }
    
        do something with v[i]...
    }
    Is the part in red necessary if I exit the program right after displaying the error message?

  2. #2
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    If it exits then i guess it should be fine, cause after program exits, the memory used by it , is anyway returned back to the OS. But i don't think you can always count on that.

    Nevertheless, its always in your best interest to free what you allocate.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Most (all?) OS's should return the memory when a program exits, but if you sometime somewhere somehow program for a small embedded system this might not be the case...
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Rabble Rouser Slacker's Avatar
    Join Date
    Dec 2005
    Posts
    116
    >Is the part in red necessary if I exit the program right after displaying the error message?
    Necessary? Nope. But it's definitely a good idea, especially since nobody tries to write bad code, and good code usually gets reused. So what could terminate immediately now would probably become a library later and then you'd have a nice little memory leak.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 05:04 AM
  2. Allocate memory inside allocated memory block?
    By Heidi_Nayak in forum C Programming
    Replies: 14
    Last Post: 04-15-2009, 05:19 PM
  3. Where are pointers allocated in memory?
    By sparks in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2005, 01:52 PM
  4. Question regarding constructors and memory.....
    By INFERNO2K in forum C++ Programming
    Replies: 6
    Last Post: 05-25-2005, 12:30 PM
  5. Replies: 8
    Last Post: 10-12-2004, 12:41 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21