-2

我有这段代码,但找不到错误的来源。我想在 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)
4

1 回答 1

2

您忘记了C 字符串中的空终止符

names[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.

于 2013-04-28T18:34:19.193 回答