snprintf with same src and dst

S

Shankar

#include<stdio.h>
int main()
{
char str1[5]="abcd";

.... snprintf(str1, 5, "%s", str1);

printf("\nOutput=\"%s\"\n", str1);

return 0;
}

Questions:
1. Whats the output of this program and why?
2. Why is it different when I use sprintf(str1, "%s", str1); ?
 
D

David Resnick

#include<stdio.h>
int main()
{
char str1[5]="abcd";

... snprintf(str1, 5, "%s", str1);

printf("\nOutput=\"%s\"\n", str1);

return 0;

}

Questions:
1. Whats the output of this program and why?
2. Why is it different when I use sprintf(str1, "%s", str1); ?

Both sprintf and snprintf say in the standard "If copying takes place
between objects that overlap, the behavior is undefined". These are
thus not really good questions... You can see what happens when you
run your program (may print, may crash, etc). Could change tomorrow
or if you run it again or if you use a different compiler or standard
library...
 
S

Shankar

#include<stdio.h>
int main()
{
char str1[5]="abcd";
... snprintf(str1, 5, "%s", str1);
printf("\nOutput=\"%s\"\n", str1);
return 0;

Questions:
1. Whats the output of this program and why?
2. Why is it different when I use sprintf(str1, "%s", str1); ?

Both sprintf and snprintf say in the standard "If copying takes place
between objects that overlap, the behavior is undefined".  These are
thus not really good questions...  You can see what happens when you
run your program (may print, may crash, etc).  Could change tomorrow
or if you run it again or if you use a different compiler or standard
library...

Thanks for the clarification. I hadn't read the standards for these
but the man pages didn't have any details about such undefined
behaviour. I was trying to use snprintf() with overlapping memory as
an improvised form of strcat, where I could achieve the functionality
of multiple strcat calls with a single snprintf(str1,len, "%s%s%s%d",
str1, str2, str3, int1); But I guess its wrong.
 
I

Ike Naar

I was trying to use snprintf() with overlapping memory as
an improvised form of strcat, where I could achieve the functionality
of multiple strcat calls with a single snprintf(str1,len, "%s%s%s%d",
str1, str2, str3, int1); But I guess its wrong.

It's undefined behaviour. But you can to this:
sprintf(str1+strlen(str1), len-strlen(str1), "%s%s%d", str2, str3, int1);
 
I

Ike Naar

It's undefined behaviour. But you can to this:
sprintf(str1+strlen(str1), len-strlen(str1), "%s%s%d", str2, str3, int1);

Sorry, typo. ``sprintf'' should be ``snprintf''.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top