Understanding Memory Allocation

This is a discussion on Understanding Memory Allocation within the C Programming forums, part of the General Programming Boards category; I'm new to the C language. The subject of memory allocation is especially new to me, so naturally I have ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    5

    Understanding Memory Allocation

    I'm new to the C language. The subject of memory allocation is especially new to me, so naturally I have a few questions.

    I'm going to base a couple of my questions on the following sample program. It will return a NULL terminated string of plus characters.

    Code:
    char *doTest(int length) {
            char *test = malloc(sizeof(char));
            char *reallocation = NULL;
            int i = 0;
            int size = 1;
    
            if (test == NULL) {
                    return NULL;
            }
    
            for (i = 0; i < length; i++) {
                    size = size + sizeof(char);
                    reallocation = realloc(reallocation, size);
    
                    if (reallocation == NULL) {
                            free(test);
                            return NULL;
                    }
    
                    test = reallocation;
                    test[i] = '+';
            }
    
            test[i] = 0;
    
            return test;
    }
    
    int main(void) {
            char *test = doTest(5);
    
            if (test != NULL) {
                    printf(test);
            }
    
            free(test);
    
            return 0;
    }
    1. In doTest, I used two pointers for memory reallocation. Both pointers should point to the same memory location. If realloc fails, I can avoid a memory leak by freeing the test pointer and stop. If realloc succeeds, I can set the test pointer to the reallocation pointer and continue. Is this a good strategy?

    2. As a follow-up to the question above, is the test pointer sometimes "invalid"? I think if realloc moves the memory location someplace else, the test pointer wont point to a valid location. It becomes "valid" again once I assign it to the reallocation pointer. If my statement is correct, do you have any suggestions on how to avoid this situation?

    3. I've noticed that if I allocate memory for multiple pointers, and store each pointer in an array, it's not enough to just free that array. I need to use a loop and free each pointer individually.

    Example:

    Code:
    char **doTest(void) {
            char **array = malloc(sizeof(char *) * 2);
    
            array[0] = malloc(sizeof(char) * 7);
            array[0] = "Test 1";
            array[1] = malloc(sizeof(char) * 7);
            array[1] = "Test 2";
    
            return array;
    }
    
    int main(void) {
            char **test = doTest();
    
            for (i = 0; i < 2; i++) {
                    free(test[i]);
            }
    
            free(test);
    
            return 0;
    }
    Note: I would normally check for NULL above, but for clarity, I left that out.

    It would be tedious to include the loop and two free calls more than once. A function would be convenient. In a C library, is it common to include functions for freeing returned pointers?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    1) Yes, you should always use a secondary pointer for realloc. Because if it fails, and you're using only one pointer, you've just lost whatever data you had before.

    2) By this, I assume you're talking about the 'test' pointer outside the function you're reallocating in? Yes, it can be invalid if you've called realloc and haven't reassigned it. That is to say:
    Code:
    char *ptr, *ptr2;
    
    ptr = malloc( somesize );
    ptr2 = realloc( ptr, somesize );
    At this point in the code, after the call to realloc, 'ptr', is considered invalid for all sanity reasons. You don't want to do anything other than reassign it, because as of now, you have no idea if it points anywhere valid. So you should treat it as if it doesn't, unless realloc has failed, then it is still valid. That's the only time you can assume it's still valid.

    3) Correct.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    5
    Quote Originally Posted by quzah
    3) Correct.


    Quzah.
    First off, thank you.

    Did you see the question: In a C library, is it common to include functions for freeing returned pointers?

    I'm not sure what you're saying correct to. I suppose I should have made that question stand out more
    Last edited by Ragsdale85; 10-29-2005 at 01:36 AM.

  4. #4
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    868
    Quote Originally Posted by JosephRagsdale
    In a C library, is it common to include functions for freeing returned pointers?
    I'm not 100% sure what you mean here.

    Some library functions return pointers to data which the function itself dynamically allocated with malloc. In this case, a simple free(p); will suffice.

    If the library function has a more complicated type, it will likely provide a cleanup function that will destroy the allocated memory associated with it for you.

    Does that help?

  5. #5
    Registered User
    Join Date
    Oct 2005
    Posts
    5
    Thanks for posting.

    Your second scenario is what I was referring to in question 3. I should have written "best practice" instead of "common" however. In my example code under question 3, I tried to illustrate a function that required more than one free step.

    I asked this question mainly because writing functions for freeing memory seems icky to me. Perhaps I'm too accustomed to a garbage collector

  6. #6
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Quote Originally Posted by JosephRagsdale
    I asked this question mainly because writing functions for freeing memory seems icky to me.
    not really that big a deal actually, most of the code is already done for you with that handy function free().

    Perhaps I'm too accustomed to a garbage collector
    JAVA?

  7. #7
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    868
    Quote Originally Posted by caroundw5h
    not really that big a deal actually, most of the code is already done for you with that handy function free().
    Yes, but this thread is about cleaning up data structures that have had many malloc's associated with them, so you can't just do a single free() call to clean up.

  8. #8
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Quote Originally Posted by cwr
    so you can't just do a single free() call to clean up.
    true, but my point was imagine how much more annoying it would be if you had to code free from hand all the time. the function simplifies your life.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  2. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  3. C memory allocation to c++
    By markucd in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2005, 04:56 AM
  4. memory allocation ptr to array? how?
    By kokopo2 in forum C Programming
    Replies: 8
    Last Post: 09-01-2005, 05:06 PM
  5. Memory allocation and deallocation
    By Micko in forum C++ Programming
    Replies: 3
    Last Post: 08-19-2005, 06:45 PM

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