#include <stdio.h>
#include <stdlib.h>

char* format(char* buffer,size_t size,
        const char* name,int quantity,int weight){
    snprintf(buffer,size,"Item: %s Quantity: %d Weight: %d",name,quantity,weight);
    return buffer;

int main()
    char *buffer = (char*)malloc(90);


    return 0;


When i run the above program, i expect the output

 Item: Axle Quantity: 25 Weight: 45

But the output i got is

 Item : A

Can someone help me.

2 Years
Discussion Span
Last Post by Moschops

buffer is a char pointer, so sizeof(buffer) is the size of a char*, which is typically 4 or 8.

If you passed in the number 8, then we would expect to see eight bytes written. One char takes up one byte, so we'd expect to see eight characters. How many did we see?

Item : A is exactly eight bytes.

It output eight characters because when you called snprintf, you told it to write no more than eight characters into buffer.

Edited by Moschops


But in buffer , i have allocated size 90 using malloc , isn't it.Then what is that for ?


Yes, you did allocate a space of 90. So maybe you should have passed the value 90 as the size parameter. Instead, you passed the value 8.

Then what is that for ?

What is what for?

Edited by Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.