gpt4 book ai didi

c++ - 大小为 1 的无效读取,将 char* 转换为 std::string

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:59 25 4
gpt4 key购买 nike

我的 test.cpp 包含以下代码。我用 valgrind 分析了它,但 valgrind 显示错误。我错过了什么?

#include<string>
#include<cstring>
#include<iostream>

void TestString(std::string & str)
{
char * tmpBuff = new char[3];
tmpBuff[0] = 'f';
tmpBuff[1] = 'o';
tmpBuff[2] = 'o';
str = tmpBuff;
delete [] tmpBuff;
}

int main(int argc, char* argv[])
{
std::string test_string;
TestString(test_string);
std::cout<<test_string;
return 0;
}

valgrind 日志

==5026== Invalid read of size 1
==5026== at 0x4A07F64: strlen (mc_replace_strmem.c:403)
==5026== by 0x347E29E14B: std::string::operator=(char const*) (in /usr/lib64/libstdc++.so.6.0.13)
==5026== by 0x4009AD: TestString(std::string&) (test.cpp:11)
==5026== by 0x4009EC: main (test.cpp:18)
==5026== Address 0x4c22043 is 0 bytes after a block of size 3 alloc'd
==5026== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==5026== by 0x400979: TestString(std::string&) (test.cpp:7)
==5026== by 0x4009EC: main (test.cpp:18)

最佳答案

tmpBuff 缺少终止符 \0

它应该包含 4 个字符:'f'、'o'、'o'、'\0'

关于c++ - 大小为 1 的无效读取,将 char* 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com