Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Behavior of sprintf and snprintf is different when we use same source and destination?

Tags:

c

printf

I have a simple code which uses sprintf

    #include <stdio.h>

    int main()
    {

            char str_src [1024]={"Hello"};
            sprintf(str_src,"%s%s",str_src,"hiiiiiiiiiii");
            printf("result = %s",str_src);  

    }

When i compile i get correct result :

result = Hellohiiiiiiiiiii

But since sprintf is unsecure, i decided to change this to snprintf. I thought it would be really simple. I changed sprintf to snprintf like below

snprintf(str_src,1024,"%s%s",str_src,"hiiiiiiiiiii");

Now If i compile and run the code, i get different result

result = hiiiiiiiiiii

I face this problem if i use str_src as 4th parameter (as a value to %s). Its suprising why the behavior of snprintf is different than sprintf?

like image 595
Nasir Avatar asked Nov 30 '22 20:11

Nasir


1 Answers

It's undefined behavior to use the same buffer both as destination and source.

From the C11 specification (7.21.6.6/2):

If copying takes place between objects that overlap, the behavior is undefined.

The same is said for snprintf (7.21.6.5/2), and also on the va_list variants as well.

Unfortunately it's all to common in running code, but it can't really be relied on to work.

like image 71
Some programmer dude Avatar answered Dec 06 '22 20:12

Some programmer dude