What can cause a segmentation fault using delete command in C++?

I've written a program that allocates a new object of the class T like this:

T* obj = new T(tid);  

where tid is an int

Somewhere else in my code, I'm trying to release the object I've allocated, which is inside a vector, using:

delete(myVec[i]);  

and then:

myVec[i] = NULL;

Sometimes it passes without any errors, and in some cases it causes a crash—a segmentation fault.

I've checked before calling delete, and that object is there—I haven't deleted it elsewhere before.

What can cause this crash?
Это мой код для вставки объектов типа T в вектор:

_myVec is global

int add() {     

int tid =  _myVec.size();  
T* newT = new T (tid);  
    if (newT == NULL){  
        return ERR_CODE;  
    }  
    _myVec.push_back(newT);  
//  _myVec.push_back(new T (tid));  

    return tid;  
} 

как есть - программа иногда дает сбой.
Когда я заменяю строку push_back строкой с комментариями и оставляю остальное как есть - все работает.

но когда я заменяю этот код на:

int add() { 

int tid =  _myVec.size();  
    if (newT == NULL){  
        return ERR_CODE;  
    }  
    _myVec.push_back(new T (tid));  

    return tid;  
}  

, происходит сбой на другом этапе ...

newT во втором варианте не используется, и все же - изменяет весь процесс ... что здесь происходит ?

9
задан Brian Tompsett - 汤莱恩 21 July 2015 в 18:16
поделиться