Program crashes after deleting the pointer
-
wrote on 9 Apr 2019, 06:11 last edited by
QList<QPair<char,int>> inferenceResult; QPair<char,int> *tempInferenceResult; qDebug()<<"Inside connectivity function"; inferenceResult = //Output from some function qDebug()<<"Inference result in connectivity"<<inferenceResult; if(i==0){ tempInferenceResult = &inferenceResult[0]; tempInferenceResult->second = 0; tempInferenceResult = &inferenceResult[2]; tempInferenceResult->second = 0; } qDebug()<<"Temp Inference result"<<*tempInferenceResult; **delete tempInferenceResult;** ---------- ------line of codes------ -----------------------
In the above code i am trying to modify the value of list of Qpair using pointer of type QPair;
My problem is that when i delete the pointer my program crashes;
There are also other approaches like inferenceResult[0].second = 0 instead of using pointer but i wanted to know the exact problem with the approach and how to resolve.
Thanks -
Hi
You take a reference to the inline structure of the list.QList<QPair<char,int>> inferenceResult;
Its not pointer to pair, but a pair. Directly.
then
tempInferenceResult = &inferenceResult[0];Points to the pair In the list. (inside list)
delete tempInferenceResult; // try to delete something INSIDE the list which
only list can do in a safe manner. -
QList<QPair<char,int>> inferenceResult; QPair<char,int> *tempInferenceResult; qDebug()<<"Inside connectivity function"; inferenceResult = //Output from some function qDebug()<<"Inference result in connectivity"<<inferenceResult; if(i==0){ tempInferenceResult = &inferenceResult[0]; tempInferenceResult->second = 0; tempInferenceResult = &inferenceResult[2]; tempInferenceResult->second = 0; } qDebug()<<"Temp Inference result"<<*tempInferenceResult; **delete tempInferenceResult;** ---------- ------line of codes------ -----------------------
In the above code i am trying to modify the value of list of Qpair using pointer of type QPair;
My problem is that when i delete the pointer my program crashes;
There are also other approaches like inferenceResult[0].second = 0 instead of using pointer but i wanted to know the exact problem with the approach and how to resolve.
Thanks@Kira
well obviously, tempInferenceResult is not it's own object instance but it references part of the memory of one of your list items.By deleting it you invalidate part of the allocated memory of that list item.,
-
wrote on 9 Apr 2019, 11:29 last edited by
Thanks for the explanation
1/4