Thread: Proper way to free a pointer returned from a function

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2022
    Posts
    8

    Proper way to free a pointer returned from a function

    I am going through the Understanding and Using C Pointers book and came across one example function for combining variables into a single buffer using snprintf.

    There is no example main for the problem within the book (it just says to pass a buffer and its size and that a pointer is returned). So I tried to make my own main()/client for the function and I am unsure of the best way to do it.

    Here is the function:
    Code:
    char* format(char *buffer, size_t size, const char* name, size_t quantity, size_t weight) {
        snprintf(buffer, size, "Item: %s  Quantity: %zu  Weight: %zu", name, quantity, weight);
        return buffer;
    }

    And here are the two ways that I tried calling it:

    Method 1:

    Code:
    
    int main () {
        char *buffer = malloc(sizeof(char) * 1024);
        printf("%s\n",format(buffer,1024,"Axle",25,45));
        free(buffer);
        return 0;
    }
    
    Method 2:

    Code:
    int main () {
        char buffer[128];
        printf("%s\n",format(buffer,sizeof(buffer),"Axle",25,45));
        return 0;
    }
    
    I think it's pretty clear that Method 1 requires free() because of the use of malloc().

    But I am confused about the second example. A pointer has been returned from format(), but I don't think I can free the buffer as I have declared it with a fixed size.

    Which is the correct way to call the function? In the second example, does anything need to be freed?
    Last edited by madcat; 05-21-2022 at 10:56 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What happens with returned pointer
    By datswd in forum C Programming
    Replies: 3
    Last Post: 05-01-2019, 11:35 PM
  2. using the value returned from an int type function
    By LAURENT* in forum C++ Programming
    Replies: 5
    Last Post: 08-28-2014, 11:12 AM
  3. which is the proper way to use free in this example?
    By c_seeker in forum C Programming
    Replies: 3
    Last Post: 01-16-2014, 08:21 AM
  4. Wrong returned pointer
    By intmail in forum C Programming
    Replies: 3
    Last Post: 03-31-2007, 05:24 AM
  5. Returned value with operator overloaded function???
    By silk.odyssey in forum C++ Programming
    Replies: 8
    Last Post: 05-12-2004, 11:46 AM

Tags for this Thread