Why I had a segmentation fault using copy assignment C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why I had a segmentation fault using copy assignment C++

Reading a book, I was trying to understand how copy assignment works. Here is the code: https://code.sololearn.com/c6A131A12a1A Basically is a very simple Vector that allocates dynamic memory, but I have a problem, I have a segmentation fault, using -fsanitize=address tells me that the error is at line 100. Here is the error: AddressSanitizer: attempting free on address which was not malloc()-ed: Which I don't understand why that error, if I delete line 100, error is gone and my code works, I'm able to print the copied values, but I think that the old memory still there. How can I solve this? I googled some examples and all of them uses delete[] var.

8th Feb 2021, 5:53 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
3 Answers
+ 4
I'm guessing that was because you were trying to point <element> to another memory block address <new_elements> while in fact <element> had been released (deleted). I guess maybe you can try to resize <element> instead, rather than allocating <new_elements>. After all, previous contents in <element> is going to be overwritten with elements from <v>.
8th Feb 2021, 6:27 AM
Ipang
+ 2
Ipang thanks for answer me! I figure out the solution, the sanitizer is clear "attempting to free on address which was not malloc()" In the line 145, the constructor that is called Vector v; doesn't allocate any memory so... Is trying to delete memory that is not allocated. I had two options, find a way to allocate memory when Vector v; constructor is called or just do Vector v(n). Doing that now I had memory allocated and can be deleted.
8th Feb 2021, 6:41 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
+ 1
Good job! Eduardo Perez Regin 👍
8th Feb 2021, 6:43 AM
Ipang