使用带动态内存的strcpy()

时间:2013-12-10 21:08:45

标签: c++ valgrind dynamic-memory-allocation strcpy

我的代码运行正常,没有内存泄漏。但是,我收到了valgrind错误:

==6304== 14 errors in context 4 of 4:
==6304== Invalid write of size 1
==6304==    at 0x4A0808F: __GI_strcpy (mc_replace_strmem.c:443)
==6304==    by 0x401453: main (calc.cpp:200)
==6304==  Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304==    by 0x401431: main (calc.cpp:199)

==6304== 4 errors in context 2 of 4:
==6304== Invalid read of size 1
==6304==    at 0x39ADE3B0C0: ____strtod_l_internal (in /lib64/libc-2.12.so)
==6304==    by 0x401471: main (calc.cpp:203)
==6304==  Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304==    by 0x401431: main (calc.cpp:199)
除了初始地址

之外,

错误1和3分别与2和4相同

这些错误意味着什么,我该如何修复它们?

 int main(){

    //Dlist is a double ended list. Each Node has a datum,
    //a pointer to the previous Node and a pointer to the next Node
    Dlist<double> hold;
    Dlist<double>* stack = &hold;

    string* s = new string;
    bool run = true;
    while (run && cin >> *s){

        char* c = new char;
        strcpy(c, s->c_str());   //valgrind errors here

        if (isdigit(c[0]))
            stack->insertFront(atof(c));

        else{
            switch(*c){
                //calculator functions
            }

        delete c;
        c = 0;
  }
delete s;
s = 0;

4 个答案:

答案 0 :(得分:3)

有很多一般无害的警告,valgrind将从stdlib函数抛出,因为它们“欺骗”了一点。但这是 的情况:

char* c = new char; // this is bad

只分配一个char - 而不是chars的缓冲区,试试:

char* c = new char[s->size()+1];

然后将删除更改为:

delete [] c;

答案 1 :(得分:3)

char * c = new char; c的大小是1,要复制甚至1个字符的字符串,你需要两个字符长的缓冲区(第二个字符来保存空终止符)

答案 2 :(得分:2)

就在这里:

    char* c = new char;

你只分配一个字符。改为分配数组:

    char* c = new char[str->length() + 1];

还记得改为调用delete []。您分配+1以为字符串的空终止创建空间。

答案 3 :(得分:1)

    char* c = new char;

您正在分配一个char,然后将一个字符串复制到该内存中,该内存太长而不适合。你需要分配一个足够大的数组。