标题。 我正在使用的功能是这样的:
void GetVideoCardInfo(int* memoryVar, char* cardName)
{
strcpy_s(cardName, 128, m_videoCardDescription);
*memoryVar = m_videoCardMemory;
return;
}
m_videoCardDescription是一个“ 128个字符长”的字符数组,其中包含我的视频卡的描述。这是我在调用函数的地方:
bool writeGPUnameDesc() {
char cardDesc;
int cardMem;
m_D3D->GetVideoCardInfo(&cardMem, &cardDesc);
std::ofstream myfile;
myfile.open("gpuNameAndDesc.txt");
myfile << "Graphics card name: " << cardDesc;
myfile << " - Graphics card memory: " << cardMem;
myfile.close();
return true;
}
当我运行程序时,会弹出一个消息框,提示运行时检查失败#2 和标题。如果有人可以帮助,请先感谢。
答案 0 :(得分:5)
您要将128个字符复制到char cardDesc
中,该字符仅代表1个字符。
您应将cardDesc
的类型更改为字符数组:
char cardDesc[128];
// ...
m_D3D->GetVideoCardInfo(&cardMem, cardDesc);
// ^ no &
答案 1 :(得分:0)
std::string GetVideoCardInfo(int & memoryVar)
{
memoryVar = m_videoCardMemory;
return m_videoCardDescription;;
}
bool writeGPUnameDesc() {
int cardMem;
std::string cardDesc = m_D3D->GetVideoCardInfo(cardMem);
std::ofstream myfile;
myfile.open("gpuNameAndDesc.txt");
myfile << "Graphics card name: " << cardDesc;
myfile << " - Graphics card memory: " << cardMem;
myfile.close();
return true;
}
strcpy_s(cardName, 128, m_videoCardDescription);
是一个公然的谎言。 cardName
的大小正好是一个字符。如果您撒谎strcpy_s
,则对其进行额外的检查以确保您不会超出缓冲区的范围,将无济于事。
替换
char cardDesc;
与
char cardDesc[129];
更好的方法完全摆脱了magic numbers。
在文件顶部附近
namespace // annonymous namespace. Contents will not leak out of the file
{
constexpr int MAX_CARD_NAME_LENGTH = 129 // 128 plus room for nul terminator
}
然后
void GetVideoCardInfo(int* memoryVar, char* cardName)
{
strcpy_s(cardName, MAX_CARD_NAME_LENGTH, m_videoCardDescription);
*memoryVar = m_videoCardMemory;
return;
}
和
bool writeGPUnameDesc() {
char cardDesc[MAX_CARD_NAME_LENGTH]; // now an array
int cardMem;
m_D3D->GetVideoCardInfo(&cardMem, cardDesc); // don't need to take address of array
std::ofstream myfile;
myfile.open("gpuNameAndDesc.txt");
myfile << "Graphics card name: " << cardDesc;
myfile << " - Graphics card memory: " << cardMem;
myfile.close();
return true;
}