2

I have a program in C as followings:

char str[50] = {0};
int a = 15;
sprintf(str, "%d", a);
printf("%s\n", str);

It can get the correct result -- 15. But if I use gdb to check the sprintf() function step by step, "sprintf.c: No such file or directory." is shown and then it is killed. Why that happens? Actually, I used the sprintf() function in another project and now it occurs overlap. I doubt if there any dangers to use the sprintf() function? How can I avoid it?

Thanks in advance!

0

1 Answer 1

1

You can use sprintf (but beware, it is unsafe so obsolete, and you should use snprintf, e.g. snprintf(str, sizeof(str), "%d", a); in your case).

It is just that, because your libc was not compiled with debug information, you cannot step inside the execution of sprintf (except by stepping on individual machine instructions).

The danger of sprintf is well known, it can make a buffer overflow. This is why you should not use it and use snprintf instead (or, if your platform has it and you want a dynamically allocated string, asprintf(3) which is available on most Linux systems).

BTW the Linux man page sprintf(3) explicitly says:

   Because sprintf() and vsprintf() assume an arbitrarily long string,
   callers must be careful not to overflow the actual space; this is
   often impossible to assure.  Note that the length of the strings
   produced is locale-dependent and difficult to predict.  Use
   snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).

It is sometimes quite useful to take into account the result of snprintf (which is the number of bytes actually needed for the computed string, which could be larger than the given size limit enforced on the result).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.