Update:
I edited the copy_entry function as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int journal_entry::copy_entry(const journal_entry & copy_from)
{
if (!copy_from.title || !copy_from.notes)
{
return 0;
}
else
{
this->title = new char[8000]; //this originally read new char[strlen(copy_from.title) + 1)- I changed it
strcpy(this->title, copy_from.title); //while troubleshooting; made no diff
this->notes = new char[8000];
strcpy(this->notes, copy_from.notes);
return 1;
}
}
|
This resulted in these errors in valgrind, which came up immediately after this code executes:
==4530== Invalid write of size 1
==4530== at 0x483E0AC: strcpy (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4530== by 0x1092B2: journal_entry::copy_entry(journal_entry const&) (cs163_entry.cpp:16)
==4530== by 0x10980F: list::add(journal_entry&) (cs163_list.cpp:14)
==4530== by 0x1095A6: main (cs163_lab2.cpp:34)
==4530== Address 0x4dba601 is 0 bytes after a block of size 1 alloc'd
==4530== at 0x483AE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4530== by 0x10927B: journal_entry::copy_entry(journal_entry const&) (cs163_entry.cpp:15)
==4530== by 0x10980F: list::add(journal_entry&) (cs163_list.cpp:14)
==4530== by 0x1095A6: main (cs163_lab2.cpp:34)
==4530==
==4530== Invalid write of size 1
==4530== at 0x483E0BE: strcpy (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4530== by 0x1092B2: journal_entry::copy_entry(journal_entry const&) (cs163_entry.cpp:16)
==4530== by 0x10980F: list::add(journal_entry&) (cs163_list.cpp:14)
==4530== by 0x1095A6: main (cs163_lab2.cpp:34)
==4530== Address 0x4dba607 is 6 bytes after a block of size 1 alloc'd
==4530== at 0x483AE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4530== by 0x10927B: journal_entry::copy_entry(journal_entry const&) (cs163_entry.cpp:15)
==4530== by 0x10980F: list::add(journal_entry&) (cs163_list.cpp:14)
==4530== by 0x1095A6: main (cs163_lab2.cpp:34)
These are the same errors I got rid of by using malloc to allocate the memory- any advice on what I did wrong would be much appreciated!
I can see that the allocated memory is too short for what is being written- the thing that confuses me is that no matter how I change the allocated amount (Most recently by simply specifying 8000 rather than using strlen), the errors remain the same. So I think that I have a fundamental misunderstanding of what is happening here with the memory allocation.
Version: g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008