Joey Joey - 1 month ago 9
C++ Question

Testing nullptr in Char Array (C++)

This is bothering my a great deal, but I was trying to do an exercise for The C++ Programming Language exercises, and the question was to simply find the size and length of a char[] array, which I did, however it encounters problems when I try to verify that it's a valid pointer:

void size_length(const char* p, int& size, int& length)
{
//I don't know why, but this causes all entries to return 0
if (!p) size = 0; length = 0; return;
//Copy the pointer, as I want the original intact
const char* cp = p;
while (*cp++) ++size; ++length;
++size; //Null character
size *= sizeof(char); //For portability
}

int main()
{
char* str{ new char[15]{"A short string"} };
int s{ 0 }, l{ 0 };
size_length(str, s, l);
cout << "Size: " << s << endl << "Length: " << l << endl;
}


In the second line of size_length() when I try to verify I have a legal pointer, such as if I passed a free store nullptr, it causes ALL attempts to register as invalid and returns 0, 0 (I placed several statements on one line to save space here). I've tried variations of the statement and passed many different things, but it all returns 0, 0. If I remove the line, the program works fine, however!

If anyone could tell me what it is I'm doing wrong and/or why I shouldn't be testing for nullptr in apparently THIS specific circumstance (I'm trying to do the right thing by testing validity) I would appreciate it.

Answer

For a start, you should be aware that:

if (!p) size = 0; length = 0; return;

is equivalent to:

if (!p)
    size = 0;
length = 0;
return;

In other words, it zeroes length and returns no matter what!

If your intent is to make all three statements conditional, you need:

if (!p) { size = 0; length = 0; return; }

which equates to:

if (!p) {
    size = 0;
    length = 0;
    return;
}

Ditto with:

while (*cp++) ++size; ++length;

in that the ++length is currently executed once after the loop finishes.

And, as an aside, I love your statement "for portability" :-) By definition, sizeof(char) is always one so there's absolutely no reason why your code isn't portable without that identity multiplication.