Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault after delete[] on base class pointer [duplicate]

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?

like image 422
user3617992 Avatar asked Jan 07 '18 13:01

user3617992


People also ask

What causes segmentation fault with pointers?

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.

What are three kinds of pointers that can cause a segmentation fault?

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.

Does dangling pointer cause segmentation fault?

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).

What causes Segfault in C++?

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.


1 Answers

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.

like image 140
StoryTeller - Unslander Monica Avatar answered Sep 18 '22 14:09

StoryTeller - Unslander Monica