Where does sprintf store its result?

If I have the following code, where is the sentence stored in sprintf

?

Is it malloc

stored in 100 bytes , or is it stored somewhere else and the pointer is store

now pointing to the new location?

char *store = malloc(100); 
int num = 77;
sprintf(store, "the number was: %d", num);

      

+3


source to share


3 answers


I agree with the other answers here; let me imagine how you can find the answer to questions like this yourself.

In C, function arguments are passed by value. That is, a function cannot change the value of its argument. This code

sprintf(store, /* whatever */);

      

cannot change the value of a pointer store

, so it cannot point to a different location.

If a function is to change the value of a pointer, it must instead get a pointer to a pointer. It happens that sprintf

it only has such a variant, called asprintf

(because it highlights + sprintf):



int asprintf(char **strp, const char *fmt, ...);

      

As you can see, its first parameter is a pointer to a pointer, so it can point to a pointer somewhere else.

For reference, here is the declaration for sprintf

:

int sprintf ( char * str, const char * format, ... );

      

+4


source


sprintf

does not allocate memory on its own - it just stores its input in the previously allocated buffer. In your case, this is indeed the buffer that you allocated when you called malloc

.



+5


source


It is stored in 100 bytes provided malloc

.

+1


source







All Articles