In my code I use a method getNumberOfP_ForAdd(). This method opens a file and returns a XMLDocumentWrapper*.
XMLDocumentWrapper* Tab::getNumberOfP_ForAdd()
{
QString defaultName = GuiUtil::getLastPath();
QString fileName = QFileDialog::getOpenFileName(this, "Open " + displayName + " File",
defaultName, displayName + " Files (*." + fileSuffix + ")", 0, 0);
if (fileName.isNull() || fileName.isEmpty()) {
qDebug() << "Load" << displayName << "aborted.";
return NULL;
}
GuiUtil::setLastPath(fileName);
// Open file
XMLDocumentWrapper* inputDoc = XMLDocumentWrapper::readFromFile(fileName);
if (inputDoc == NULL) {
qDebug() << "Load" << displayName << "aborted.";
return NULL ;
}
return inputDoc;
}
When I try to read a file there are 2 things I check first: Wheather
(fileName.isNull() || fileName.isEmpty())
and
(inputDoc == NULL)
If these statements are true I do
return NULL;
Can I simply return a NULL-Ptr or would I run into problems in doing so? Do I have to free that pointer again?
You can return a null pointer if your function's return type is a pointer.
If the caller checks the return value and handles the case where the return value is null - then there shouldn't be any problem. if the caller tries to dereference this pointer, then problems do occur.
The fact that the function returns a pointer doesn't necessarily mean the developer needs to free the memory. the pointer could point to anything, including stack and global variables. The developer should look at the function's documentation to make sure what to do with the return value. Anyway, there is no problem in deleting null pointers, but again , one should look if she/he needs to deallocate something at the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With