Thread: freeing malloc

  1. #1
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534

    freeing malloc

    It has been a long time since I have done any programming, and so my knowledge is quite rusty. Say I had a function where I did something like this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void foo(char **txt_ptr)
    {
        enum {
            BUF_MAX = 25
        };
        char *buffer = malloc(BUF_MAX * sizeof *buffer);
    
        if (buffer == NULL) {
            puts("No memory for you!");
            exit(EXIT_FAILURE);
        }
    
        strcpy(buffer, "A random string");
        *txt_ptr = buffer;
    }
    
    int main(void)
    {
        char *textp = NULL;
        foo(&textp);
        printf("\n&#37;s\n\n", textp);
    
        return 0;
    }
    Would I do

    Code:
    free(textp);
    from main? Would this properly free the memory I allocated in 'foo'?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes, that would be correct.
    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
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Yes. It's a - ok.

  4. #4
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Great! Thanks guys!

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. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. 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
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM