开发者

Segmentation fault during processing delete command

开发者 https://www.devze.com 2023-02-17 17:46 出处:网络
I have a program that using a vector (called _library) that holds objects of the class \'thread\' that I\'ve created (holds a set of data, and allocating some stuff in its Constructor).

I have a program that using a vector (called _library) that holds objects of the class 'thread' that I've created (holds a set of data, and allocating some stuff in its Constructor).

Now, I've tried to run my program, calling this line:

delete (_library[_currRunning]);

->and got the scary Segmentation fault message from my compiler.

I don't understand what is the problem here, since I perform boundary checks, and - what's more surprising: it works on other inputs, when I've tested it before!

In general, what can cause a segmentation fault when using 'delete', and how could I prevent such errors in my code?

In addition, I have a destructor for the 'thread' class, having this single line:

delete (_stack); 

where _stack is a char* that I've allocated in the Ctor.

Here're my 'thread' object fields:

char* _stack;  
int _tid;  
void (*_thread_f开发者_如何学JAVAunc)(void);  
sigjmp_buf _jbuf;  
Sync* _sync;  
int _status; 

In 'thread' Ctor, there is (between others) this line:

_stack = new char[STACK_SIZE]; 

And this is its Dtor:

delete[] _stack;    

In my big program, i have this declaration:

vector<thread*> _library;  

Is there any problem of using 'delete' inside my Destructor, instead of using 'free'?


With the very little info you've provided I would assume that you are double freeing one of the thread objects. Your problem is not with vector but with your lifetime management of the threads.


if you allocated _stack like so:

_stack = new char[SOME_LEN];

you want to delete it with

delete[] _stack;

note the [] after delete that's needed when you allocate an array.


Assuming _libray[_currRunning] contains a pointer, either:

  1. _library[_currRunning] is an invalid address
  2. _library[_currRunning] has already been deleted

If it's the second case, make sure you remove the element from the vector (using erase) after you delete it.

EDIT: By "invalid", I mean the address to an object that wasn't created with new.


You don't need to delete any objects of a vector- it will clean them up itself. Likely, you meant to use vector.erase() to remove it.


Unless your _currRunning is a pointer created at some point with new, delete will have repercussions. E.g.

void func()
{
   int a = 1;
   int* b = new int(2);
   delete b; // Ok, deleting a pointer
   delete a; // Can't delete non-pointer - should be a compilation error (?)
   delete &a; // This will call the destructor of a, but then the program 
              // will segfault when a goes out of scope at the end of this function.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消