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?