Help please:
char tmp[1000]
sprintf(tmp,“123”);
sprintf(tmp,"%s 456", tmp);
cout << tmp << endl;
In OpenSUSE 10.2 result: 123 456
In OpenSUSE 11 result: 456
Why there is this problem in OpenSUSE 11?
Help please:
char tmp[1000]
sprintf(tmp,“123”);
sprintf(tmp,"%s 456", tmp);
cout << tmp << endl;
In OpenSUSE 10.2 result: 123 456
In OpenSUSE 11 result: 456
Why there is this problem in OpenSUSE 11?
Hi,
Couldn’t test it in Open Suse 11 yet, but the same code works fine in Open Suse 10.3.
This is the code I tried:
#include <iostream>
using namespace std;
int main()
{
char tmp[1000];
cout << “My temp string: “;
sprintf(tmp,“123”);
sprintf(tmp,”%s 456”, tmp);
cout << tmp << endl;
return 0;
}
Output (As expected):
My temp string: 123 456
I’ll try in Open Suse 11 soon. Let’s see if I can reproduce the problem.
Regards.
Works fine here on 11.0. Some changes are needed to make it a complete C++ program
#include <iostream>
#include <stdio.h>
main() {
char tmp[1000];
sprintf(tmp,"123");
sprintf(tmp,"%s 456", tmp);
std::cout << tmp << std::endl;
}
“Works fine?” Dudes, where did you learn C/C++…
sprintf(tmp, "%s 456", tmp);
You are trying to write into tmp at the same time you read out of it, which is not defined. sprintf can tamper with the buffer you gave it as the first argument in any way it sees fit (like zeroing it) before actually processing any of the arguments.
I realise that it’s not kosher C/C++, I was merely disputing the OP’s claim that he got only 456 on 11.0.
Hi,
Tested also in Open Suse 11. The same output as in Open Suse 10.3:
123 456
Even so, the behavior is not consistent.
Thus, as suggested by jengelh, be on the safe side and don’t use the target buffer as source argument in the same call to sprintf.
Regards.
your code causes undefined behaviuor, hence the results are not consistent