Access to field results in dereference of a null pointer - c++

I get this warning when analyzing the code with XCode 4.6 and I don't get it.
VanishingPointInfo* vpClosestToCenterLine = NULL;
for (vector<VanishingPointInfo>::iterator vpInfo = lineCrossings.begin(); vpInfo != lineCrossings.end(); vpInfo++)
{
if (vpClosestToCenterLine == NULL || vpInfo->diffToMiddle < vpClosestToCenterLine->diffToMiddle)
{
vpClosestToCenterLine = &(*vpInfo);
}
}
XCode complains that the access to vpInfo->diffToMiddle results in a dereference of a NULL pointer. But that is the iterator...

Xcode is flagging the message to warn that the is an error if vpInfo has a null value, if it does then the substructures inside vpInfo are all invalid. To fix the warning you can put an existence check before going through the logic requiring access to the substructures. ....
if (vpInfo) {
VanishingPointInfo* vpClosestToCenterLine = NULL;
for (vector<VanishingPointInfo>::iterator vpInfo = lineCrossings.begin(); vpInfo != lineCrossings.end(); vpInfo++)
{
if (vpClosestToCenterLine == NULL || vpInfo->diffToMiddle < vpClosestToCenterLine->diffToMiddle)
{
vpClosestToCenterLine = &(*vpInfo);
}
}}

Related

C/C++ Dereference error: Dereference before null check

In the function below I am facing a Dereference error before null check. In the line
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
There is an error which states directly dereferencing pointer pTCGKS. And also in the line
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
there is an error which states Dereference before null check (REVERSE_INULL)
check_after_deref: Null-checking pTCGKS suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
Stat_t SEC_COD_SLOW SEC_KM_TCG_Activ(SEC_KM_TCGKeySet_t *pTCGKS, uint32_t rangesSUM, SEC_KM_DefaultKeySet_t *pDefaultKS)
{
Status_t status = STATUS_OK;
uint32_t rangeIndex = 0;
const SEC_KM_KDF_t *pDigestNID = SEC_KM_GetAnybodyDigest();
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
const SEC_KM_KDF_t *pDigestAID = SEC_KM_TCG_GetSessionCredentials();
SEC_ASSERT_DEBUG(SEC_KM_TCG_GetSessionUserID() == SEC_KM_Admin1);
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
// Generate Key Chains for all TCG authorities for Original Opal scheme
status = SEC_KM_TCG_Generate(pTCGKS, pDigestNID, pDigestAID);
if (status != STATUS_OK)
{
return status;
}
// Rewrap SDEK from default key storage into Global Range of TCG
status = SEC_KM_RewrapSDEK(&pDefaultKS->SDEKw, &pDefaultKS->keySet.RKEKw, &pDefaultKS->keySet.PKEKw, pDigestNID,
&pTCGKS->DEK[GDEK].SDEK.w, &pAdmin1KEKs[RKEKG].w, &pAdmin1KEKs[PKEK].w, pDigestAID);
if (status != STATUS_OK)
{
return status;
}
status = SEC_KM_TCG_ConvertToSUM(pTCGKS, pDigestNID, rangesSUM);
if (status != STATUS_OK)
{
return status;
}
// After Activation all ranges are unlocked. So unwrap all SDEKs.
for (rangeIndex = 0; rangeIndex < TCG_MAX_RANGE_KEYS; rangeIndex++)
{
status = SEC_KM_TCG_UnwrapUnlockedSDEK(pTCGKS, rangeIndex);
if (status != STATUS_OK)
{
return status;
}
}
return status;
}
It's exactly what it says.
First you dereference pTCGKS, then you check that it isn't null.
Compilers can (and will) optimise out a "late" null check as being effectively redundant for any well-defined program, making your assertion potentially useless.
Move it to before your dereference.
The SEC_ASSERT_MODEL checks for NULL after the line that references it. If pTCGKS is null a runtime error will occur before that check, so it serves no useful purpose.
I assume SEC_ASSERT_MODEL is a precondition check macro - if that is the case you need to perform those checks before using the checked parameters:
SEC_ASSERT_DEBUG(SEC_KM_TCG_GetSessionUserID() == SEC_KM_Admin1);
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
Status_t status = STATUS_OK;
uint32_t rangeIndex = 0;
const SEC_KM_KDF_t *pDigestNID = SEC_KM_GetAnybodyDigest();
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
const SEC_KM_KDF_t *pDigestAID = SEC_KM_TCG_GetSessionCredentials();

Issue with function to check if tree is a BST

So I have a function to check if a tree is a bst(if every node only has smaller values on its left and larger values on its right). Every other function works and the problem is with this one (second one just calls helper). I think the issue has something to do with the recursive call root-left hitting null but I am not sure and even if it is not sure how to fix. Can add more code as needed. Any help is appreciated.
visual studio error i get is : R00t -> left was nullptr
other compiler: segmentation fault core dumped.
bool isBSThelper(TreeNode* R00t)
{
if (R00t == NULL)
return true;
//if (R00t->left != NULL && (R00t->info < R00t->left->info))
if (R00t->info < R00t->left->info)
return false;
//if (R00t->right != NULL && (R00t->info < R00t->right->info))
if (R00t->info > R00t->right->info)
return false;
return isBSThelper(R00t->left) && isBSThelper(R00t->right);
}
bool TreeType::isBST() const
{
return isBSThelper(root);
}
According to your comment
even with if (R00t->left != NULL || R00t->right != NULL) error persists
the problem would persist. Let me rewrite and iterate from there (since I can't comment to ask for clarification -new user). If your code was like
bool isBSThelper(TreeNode* R00t) {
if ( R00t == NULL )
return true;
if ( R00t->left != NULL || R00t->right != NULL ) {
if ( R00t->info < R00t->left->info )
return false;
if ( R00t->info < R00t->right->info )
return false;
}
return isBSThelper(R00t->left) && isBSThelper(R00t->right);
}
then you would potentially still encounter the same problem, since the expression
if (R00t->left != NULL || R00t->right != NULL) {
would still make this expression with values
R00t->left != NULL
but
R00t->right == NULL
evaluate to true.
One solution might be
To make sure R00T->left and R00t->right are either valid (pointing to a node) or NULL (preferably nullptr if you are using C++)
And code like this:
bool isBSThelper( TreeNode* R00t ) {
if ( R00t == NULL )
return true;
if ( R00t->left != NULL && R00t->info > R00t->left->info )
return false;
if ( R00t->right!= NULL && R00t->info > R00t->right->info )
return false;
return isBSThelper( R00t->left ) && isBSThelper( R00t->right );
}
And the problem would be no more. (1) is critical.
An additional note: Your code does not check
if (R00t->left != NULL && R00t->right!= NULL && R00t->left->info < R00t->right->info)
return false;
which is another property of a Binary Search Tree (or obviously using ">" instead of "<" here as you see fit).

How to protect app against read access violation while accessing to pointer's value?

I've created some chain-like structure, where one object has pointers to the next and previous object of a chain. The code below loops through entire chain, looks for value specified in arguments and removes matching element (if exists).
void List::removeElementByValue(int value)
{
ListMember* nextElem = this->firstValue;
while (nextElem) {
if (nextElem == NULL || nextElem == nullptr) {
break;
}
if (nextElem->value == value) {
if (nextElem->prevValue)
(nextElem->prevValue)->nextValue = nextElem->nextValue;
if (nextElem->nextValue)
(nextElem->nextValue)->prevValue = nextElem->prevValue;
delete nextElem;
this->count--;
return;
}
nextElem = nextElem->prevValue;
}
}
The problem is: I'm getting this error when I'm trying to remove non-existent value from chain.
Exception thrown: read access violation. nextElem was 0xCDCDCDCD.
Function should do nothing in that case. It happens at this line:
if (nextElem->value == value) {
As you see, I've used multiple ways to check if nextElem is correct, but I'm still getting this error. Any ways I can prevent that?
if (nextElem == NULL || nextElem == nullptr)
This will always be false when while (nextElem) is true.
nextElem = nextElem->prevValue;
This needs to use nextValue instead of prevValue.
But, most importantly, you are not updating this->firstValue if the value is found in the first element of the list, so you end up deleting the firstValue and leave it pointing at invalid memory.
Try this instead:
void List::removeElementByValue(int value)
{
ListMember* elem = this->firstValue;
while (elem) {
if (elem->value == value) {
if (elem->prevValue)
elem->prevValue->nextValue = elem->nextValue;
if (elem->nextValue)
elem->nextValue->prevValue = elem->prevValue;
// ADD THIS!!!
if (elem == this->firstValue)
this->firstValue = elem->nextValue;
delete elem;
this->count--;
return;
}
elem = elem->nextValue; // NOT prevValue!
}
}
A better solution is to not implement a linked list manually in the first place. Use the standard std::list container instead, let it do all of the hard hard for you.
#include <list>
class List
{
private:
std::list<int> values;
...
};
...
#include <algorithm>
void List::removeElementByValue(int value)
{
auto iter = std::find(values.begin(), values.end(), value);
if (iter != values.end())
values.erase(iter);
}

Why is this Haxe try-catch block still crashing, when using Release mode for C++ target

I have a HaxeFlixel project, that is working OK in Debug mode for misc targets, including flash, neko and windows. But Targeting Windows in Release mode, I'm having an unexpected crash, and surprisingly it's happening inside a try-catch block. Here's the crashing function:
/**
* Will safely scan a parent node's children, search for a child by name, and return it's text.
* #param parent an Fast object that is parent of the `nodeNamed` node
* #param nodeName the node's name or a comma-separated path to the child (will scan recursively)
* #return node's text as String, or null if child is not there
*/
public static function getNodeText(parent:Fast, nodeName:String):String {
try {
var _node : Fast = getNodeNamed(parent, nodeName);
//if (_node == null)
// return null;
// next line will crash if _node is null
var it :Iterator<Xml> = _node.x.iterator();
if ( it == null || !it.hasNext() )
return null;
var v = it.next();
var n = it.next();
if( n != null ) {
if( v.nodeType == Xml.PCData && n.nodeType == Xml.CData && StringTools.trim(v.nodeValue) == "" ) {
var n2 = it.next();
if( n2 == null || (n2.nodeType == Xml.PCData && StringTools.trim(n2.nodeValue) == "" && it.next() == null) )
return n.nodeValue;
}
//does not only have data (has children)
return null;
}
if( v.nodeType != Xml.PCData && v.nodeType != Xml.CData )
//does not have data";
return null;
return v.nodeValue;
}catch (err:Dynamic) {
trace("Failed parsing node Text [" + nodeName+"] " + err );
return null;
}
}
By enabling if (_node == null) return null; line, It's working safely again. By catching errors as Dynamic I thought I was supposed to catch every possible error type! Why is this happening? And why is it appearing in release mode?
My IDE is FlashDevelop, and I'm using HaxeFlixel 3.3.6, lime 0.9.7 and openFL 1.4.0, if that makes any difference
EDIT: I suspect this has to do with how the translated C++ code missed the Dynamic Exception. The equivalent generated C++ code is:
STATIC_HX_DEFINE_DYNAMIC_FUNC2(BaxXML_obj,_getNodeNamed,return )
::String BaxXML_obj::getNodeText( ::haxe::xml::Fast parent,::String nodeName){
HX_STACK_FRAME("bax.utils.BaxXML","getNodeText",0x4a152f07,"bax.utils.BaxXML.getNodeText","bax/utils/BaxXML.hx",56,0xf6e2d3cc)
HX_STACK_ARG(parent,"parent")
HX_STACK_ARG(nodeName,"nodeName")
HX_STACK_LINE(56)
try
{
HX_STACK_CATCHABLE(Dynamic, 0);
{
HX_STACK_LINE(57)
::haxe::xml::Fast _node = ::bax::utils::BaxXML_obj::getNodeNamed(parent,nodeName); HX_STACK_VAR(_node,"_node");
HX_STACK_LINE(63)
Dynamic it = _node->x->iterator(); HX_STACK_VAR(it,"it");
// ... Let's skip the irrelevant code
}
catch(Dynamic __e){
{
HX_STACK_BEGIN_CATCH
Dynamic err = __e;{
HX_STACK_LINE(82)
::String _g5 = ::Std_obj::string(err); HX_STACK_VAR(_g5,"_g5");
HX_STACK_LINE(82)
::String _g6 = (((HX_CSTRING("Failed parsing node Text [") + nodeName) + HX_CSTRING("] ")) + _g5); HX_STACK_VAR(_g6,"_g6");
HX_STACK_LINE(82)
::haxe::Log_obj::trace(_g6,hx::SourceInfo(HX_CSTRING("BaxXML.hx"),82,HX_CSTRING("bax.utils.BaxXML"),HX_CSTRING("getNodeText")));
HX_STACK_LINE(83)
return null();
}
}
}
HX_STACK_LINE(56)
return null();
}
What haxedefs do you have defined?
Adding these to your project.xml might help:
<haxedef name="HXCPP_CHECK_POINTER"/> <!--makes null references cause errors-->
<haxedef name="HXCPP_STACK_LINE" /> <!--if you want line numbers-->
<haxedef name="HXCPP_STACK_TRACE"/> <!--if you want stack traces-->
You might also try the crashdumper library:
https://github.com/larsiusprime/crashdumper
(Crashdumper will turn on HXCPP_CHECK_POINTER by default as part of it's include.xml, and will set up hooks for both hxcpp's errors and openfl/lime's uncaught error events)
I guess this boils down to how C++ handles null-pointer Exceptions. It doesn't!
More info here or here
That seems odd, some questions that may help solving it.
It looks like you are doing quite some assumptions on how the xml looks (doing some manual it.next()), why is that?
Why are you using this big-ass try-catch block?
How does getNodeNamed look, it seems it can return null.
Do you have an example xml to test with?

C++ Linkedlist simple question

I'm trying to check if an entity exists in a given linkedlist. This is my code:
bool LinkedList::existByID(int ID)
{
//create node to search through the list
Node * helpNode;
//start it at the top of the list
helpNode = head;
if (head == NULL)
{
return false;
}
//while the item has not yet been found
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
{
if (helpNode->data->indicatedEntity->getID() == ID)
{
//return true - the data exists
return true;
}
else
//if the data has not been found, move on
helpNode=helpNode->next;
}
//if the data has not been found and the end of the
//list has been reached, return false - the item does
//not exist
return false;
}
From the line I marked as the "problem line", the part of the if statement
(helpNode->data != NULL)
I get error CXX0017 (symbol "" not found) and error CXX0030 (expression cannot be evaluated).
This code works if there are no entities in the linkedlist - in other words, if the head is null.
The Node constructor looks like this:
LinkedList::Node::Node()
{
next=NULL;
data=NULL;
}
I've also tried it with the line:
(helpNode != NULL)
and Node constructor
LinkedList::Node::Node(){}
All combinations return the same errors. Any suggestions?
Firstly I recommend fixing a few things with your code.
In your loop you check the data member of helpNode before testing to see if helpNode is actually valid. Imagine you are on the last node - and at the end of the while the following executes - now what gets checked at the top?
helpNode=helpNode->next;
Secondly, once you've checked for helpNode, next you should check that data is valid before checking attributes of data, what if data is NULL?
And now think about what your loop is checking, it's checking that getID() != ID, and yet inside the loop you are testing for the ID, getID() == ID? does that make sense?
I recommend that in your loop, you just check that the next node and data exists, and then within the loop check that the ID matches, and return if true.
Well the line
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
might be a problem if data is NULL, because then you would be trying to access NULL->indicatedEntity
further if indicatedEntity is NULL, then you are trying to access NULL->getID()
you can rewrite it to
while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)
which doesnt look nice, but it does ensure your pointers are not null before trying to access them.