I have a snippet of code here, of which I don't understand why it results in a segmentation fault on line 22 (delete[] statement). Can you please explain this to me?
#include<iostream>
#include<memory>
class A {
size_t a[1000];
public:
virtual ~A() { }
};
class B : public A {
public:
float b;
virtual ~B() { }
};
int main(int argc, char** argv){
A *b;
b = new B[10];
delete[] b;
return 0;
}
Strangely, if class B doesn't have any member variables (i.e. I comment out the line "float b;") then the code just runs fine.
What's my mistake here?
A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.
Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address) Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted) A buffer overflow. A stack overflow.
If the memory has been reallocated to another process, then attempting to dereference the dangling pointer can cause segmentation faults (UNIX, Linux) or general protection faults (Windows).
A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.
Simply put, you have undefined behavior. You aren't providing delete[]
with a pointer you got from new[]
. You may think you do, but for the pointers to be the same in the array version, their static type has to match. You converted the pointer into a pointer to a base class.
Practically, when you don't have that added float
, your implementation probably maintains sizeof(B) == sizeof(A)
. So the destructor and deallocation function invocations don't do anything immediately harmful. But it's just as undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With