Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return a NULL-Pointer in a C++ method?

Tags:

c++

null

return

qt

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?

like image 239
user3443063 Avatar asked Aug 02 '26 22:08

user3443063


1 Answers

  1. You can return a null pointer if your function's return type is a pointer.

  2. 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.

  3. 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.

like image 112
David Haim Avatar answered Aug 04 '26 14:08

David Haim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!