我有这段代码,但找不到错误的来源。我想在char数组中存储多个名字,我必须使用char类型。我做了这个,但是这个问题出了问题。
#include <iostream>
#define MAX 2
using namespace std;
int main()
{
char **names;
names=new char* [MAX];
names[0]=new char[3];
for(int i=0;i<3;i++)
names[0][i]='a';
names[1]=new char[4];
cout<<names[0]<<endl;
for(int i=0;i<4;i++)
names[1][i]='b';
cout<<names[1]<<endl;
////////////////
for(int i=0;i<MAX;i++)
delete names[i];
delete [] names;
return 0;
}
有人可以解释为什么,我会在valgrind中得到错误吗? 没有泄漏,但是有错误。
Invalid read of size 1
==4063== at 0x4C2BFB4: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x4EC62E0: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==4063== by 0x400911: main (main.cpp:16)
==4063== Address 0x5a03093 is 0 bytes after a block of size 3 alloc'd
==4063== at 0x4C2AC27: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x4008B4: main (main.cpp:10)
==4063==
aaa
==4063== Invalid read of size 1
==4063== at 0x4C2BFB4: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x4EC62E0: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==4063== by 0x400964: main (main.cpp:20)
==4063== Address 0x5a030e4 is 0 bytes after a block of size 4 alloc'd
==4063== at 0x4C2AC27: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x4008FA: main (main.cpp:15)
==4063==
bbbb
==4063== Mismatched free() / delete / delete []
==4063== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x400992: main (main.cpp:23)
==4063== Address 0x5a03090 is 0 bytes inside a block of size 3 alloc'd
==4063== at 0x4C2AC27: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4063== by 0x4008B4: main (main.cpp:10)
答案 0 :(得分:2)
您忘记了null terminator
中的C-stringnames[0] = new char[4]; // 3 + 1 because of the null terminator
for(int i = 0; i < 3; i++)
names[0][i] = 'a';
names[0][3] = '\0';
基本上,当你使用std::cout <<
输出字符串时,valgrind报告无效的内存访问,因为输出例程不能理解C字符串的结束位置,只是保持输出超出分配的内存缓冲区的字符对于字符串。
另外,我认为这是家庭作业或其他什么,否则你会疯狂不使用std::string
。