在理论和实践中未定义的行为 [英] undefined behaviour in theory and in practice
问题描述
我有很长一段时间由别人写的大型C ++项目。它包含如下代码:
string CVersion :: GetVersionStr()const
{
string ret;
char VersionStr [100];
DWORD v1,v2,v3,Build;
GetVersion(& v1,& v2,& v3,& Build);
sprintf(VersionStr,%d。%d。%d。%d,v1,v2,v3,Build);
return string(VersionStr);
}
现在我认为因为格式说明符错误
在我的电脑上声明为 typedef unsigned long DWORD;
我的问题是:
- 代码是否包含未定义的行为?
- 是否有任何平台/情境,它不会是未定义的行为?也许对于v1的某些值是罚款?
li>
PS。这个软件是10年前用Visual Studio编写的
解决方案是的,如果DWORD是 unsigned long
。正确的格式说明符是%lu
。
由于未定义的行为正是这样,您的第二个和第三个问题有意义。
为什么不使用 std :: stringstream
,并利用 < / code>?
I have large C++ project written by someone else long time ago. It contains code like:
string CVersion::GetVersionStr() const
{
string ret;
char VersionStr[100];
DWORD v1, v2, v3, Build;
GetVersion(&v1, &v2, &v3, &Build);
sprintf(VersionStr, "%d.%d.%d.%d", v1, v2, v3, Build);
return string(VersionStr);
}
Now I think because of wrong format specifier (%d
) this code has undefined behaviour.
DWORD
on my PC is declared as
typedef unsigned long DWORD;
My questions are:
- does code contain undefined behaviour?
- Is there any platform/situation where it would not be undefined behaviour? Maybe it is fine for some values of v1?
- The software has been working correctly for long time, so can it happen that in practice, despite above is undefined behaviour, the software still works fine?
PS. This software was written something like 10 years ago using Visual Studio
解决方案 Yes, the behaviour is undefined if DWORD is an unsigned long
. The correct format specifier is %lu
.
Because undefined behaviour is exactly that, your second and third questions are not meaningful.
Why not use something like a std::stringstream
and exploit <<
?
这篇关于在理论和实践中未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!