I'm currently working a wrapper function for a network class, when I stumbled on a question. Tried googling it, but I couldn't find the answer there, so I decided to post it here.
Code:
const char* CRakPacket::GetNullTerminatedString(int MaxLength)
{
int length = strlen(data + location) + 1; // \0 included
// check if the length isn't bigger than a specified value, or that it surpasses the end of the pointer (buffer overrun)
if(length > MaxLength || location + length > size)
return 0;
// store the returned pointer because the location has to be moved later.
char* retptr = data + location;
// set the current location to the proper position.
location += length;
return retptr;
}
As you can see i'm using strlen() to check if the data buffer has no null-terminator and thus copying it would cause a buffer overrun. Now my question is this: When strlen passes outside the area of allocated memory, can it crash on certain compilers (it worked on G++), or is it better for me to make a strlen function that checks whether it's outside the allocated memory?