Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf in C resets the value of counting variable [duplicate]

Tags:

c

printf

I'm having an issue with sprintf in C resetting the value of a counter variable when I run it. Here in a nutshell is what is happening:

int count = 0;
count++;
printf("%d\n", count); // count will equal 1
char title[7];
sprintf(title, "%.3d.jpg", count);
printf("%d\n", count); // count now equals 0 again

Is this normal behavior for sprintf?

like image 878
thejeqff Avatar asked Feb 08 '14 13:02

thejeqff


People also ask

What does sprintf() do?

sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.

How does sprintf works in C?

sprintf() in C int sprintf(char *str, const char *string,...); Return: If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned . sprintf stands for “String print”.

Does Sprintf overwrite in C?

The sscanf () function and the sprintf () function are like the two sides of a coin. You can now use the sprintf() function to reassemble the string. You can use the same char array stringa- its previous value gets overwritten.

What does sprintf return?

The sprintf function returns the number of characters stored in the array s , not including the terminating null character. The behavior of this function is undefined if copying takes place between objects that overlap—for example, if s is also given as an argument to be printed under control of the ' %s ' conversion.


Video Answer


1 Answers

title is too small, sprintf is writing beyond the bounds of title, and writing into count, corrupting its value.

Note that title needs to be long at least 8 bytes: 3 for %.3d, 4 for .jpg and 1 for the terminator \0.

As Grijesh Chauhan points out, you can make sure that you never write beyond the allocated size of the string by using snprintf, i.e.:

char title[8];
snprintf(title, sizeof(title), "%.3d.jpg", count);
like image 169
smani Avatar answered Sep 29 '22 13:09

smani