0

I have not been able to find the errors in strcpy and cmp. The code works well and there is not memory leak. I just get 6 errors from 2 contexts.
I'm getting this errors using valgrind:

Invalid read of size 1
at 0x4C3D1C3: strcpy (vg_replace_strmem.c:553)
by 0x401F16: word::setData(char*)(word.cpp:53)

Address 0x5b509a8 is 0 bytes after a block of size 8 alloc'd
at 0x4C38B6F: operator new[](unsigned long) (vg_replace_malloc.c:640)
by 0x401354: load(std::basic_fstream<char, std::char_traits<char> >&) (main.cpp:58)

Invalid read of size 1
at 0x4C3E13C: strcmp (vg_replace_strmem.c:924)
by 0x4019CB: list::insert(char*) (list.cpp:57)
Address 0x5b516d5 is 0 bytes after a block of size 5 alloc'd
at 0x4C38B6F: operator new[](unsigned long) (vg_replace_malloc.c:640)
by 0x401354: load(std::basic_fstream<char, std::char_traits<char> >&) (main.cpp:58)

word.cpp

void word::setData( char *newData)
{
    if(data){
       delete [] data; 
       data = nullptr;
    }
    int sizenew = sizeof(newData); 
    data = new char [sizenew + 2]; 
    strcpy(data, newData);
}
Amy0
  • 1
  • `sizeof(newData)` does not do what you think it does. It will be either 4 or 8, depending on your CPU, even if `newData` points to the contents of the entire "Lord Of The Rings" trilogy. – Sam Varshavchik Sep 07 '22 at 01:05
  • as Sam points out the issue is caused by misuse of `sizeof`, `sizeof(newData)` is the size of char* pointer, it will be either 4 or 8 depending on your program's architecture (like x86 or x64), you should use strlen instead. – Tony_Tong Sep 07 '22 at 01:15
  • int sizenew = sizeof(newData); this will alway return 4 on x86 platform, and 8 on x64 platform. so you should use strlen(newData) instead. – Exlife Sep 07 '22 at 09:37

0 Answers0