Search code examples
c++pointersreferencenull

C++ : dereferencing NULL pointer warning


I tried to recreate strcat function as beginner, The warning is shown on the line:

dest[i] = src[j];
void strCat(char* dest, const char* src) {
        size_t len = 0, destLen = 0, srcLen = 0;
        if (dest != nullptr) {  destLen = strLen(dest);}
        if (src == nullptr) { return; }
        else { srcLen = strLen(src); }

        int j = 0;
        len = destLen + srcLen +1;
        for (size_t i = destLen; i < len; ++i)
        {
            dest[i] = src[j];
            j++;
        }

    }

I am facing this warning in Visual Studio 2022, the code is executed succesufully and the warning is not shown in the output window or error list. But in the code window, it underlined and saying "Dereferencing NULL pointer 'dest' "


Solution

  • You aren't aborting early from the function if dest is nullptr. That's why you get a compiler warning. You'd surely crash if strCat(nullptr, "foo") was invoked. Although as others have said, actual strcat may not check either pointer parameter for null.

    More pro-tips:

    • You don't need to invoke strLen. Especially not for src. You can exit the copy loop as soon as src points to a null char.

    • strcat is expected to return dest

    Quite simply we can do this:

    char* strCat(char* dest, const char* src) {
            char* result = dest;
    
            // validate parameters
            if ((dest == nullptr) || (src == nullptr)) {
                return result;
            }
    
            // advance dest to the existing null char
            while (*dest != '\0') {
                dest++;
            }
    
            // copy loop
            while (*src != '\0') {
                *dest = *src;
                dest++;
                src++;
            }
    
            // make dest null terminated
            *dest = '\0';
            return result;
    }