簡體   English   中英

使用帶動態內存的strcpy()

[英]Using strcpy() with dynamic memory

我的代碼運行正常,沒有內存泄漏。 但是,我收到了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;

valgrind會從stdlib函數中拋出一系列通常無害的警告,因為它們會“欺騙”一點。 但這不是這種情況:

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

只分配一個char - 不是chars的緩沖區,嘗試:

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

然后將刪除更改為:

delete [] c;

char * c = new char; c的大小為1,復制甚至1個字符的字符串需要兩個字符的長緩沖區(第二個字符用於保存空終止符)

就在這兒:

    char* c = new char;

你只分配一個char。 改為分配數組:

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

還記得改為調用delete []。 您分配+1以為字符串的空終止創建空間。

    char* c = new char;

您正在分配一個char,然后將一個字符串復制到該內存中,該內存太長而不適合。 你需要分配一個足夠大的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM