Home > front end >  Use of string functions with manually set NUL-terminator
Use of string functions with manually set NUL-terminator

Time:11-25

This might sound like a silly question, but I learned that sometimes, especially in C, there are things that seem obvious but aren't really safe or correct.

I have a char buffer that gets filled with text (no binary data is expected) via HTTP.

Now I want to process the request body and I think strstr() is exactly what I want.

However, strstr() needs both strings to be nul terminated.

Since I have no control over what the user will actually send, I decided to just terminate the "string" (buffer) at the end like this:

char buffer[1024];

// receive request
readHTTPRequest(buffer, sizeof(buffer));

// buffer contents is undetermined
buffer[sizeof(buffer) - 1] = 0; // always terminate buffer

const char *request_body = strstr(buffer, "\r\n\r\n");

if (request_body) {
    size_t request_body_size = strlen(request_body);
} 

Is this approach safe? Am I missing something?

CodePudding user response:

This will only work if the buffer was completely filled. If not, you'll have uninitialized bytes in between what was actually read and the last byte.

A simple way to handle this is to initialize the buffer with all zeros:

char buffer[1024] = {0};

Or, if readHTTPRequest returns the number of bytes read, use that value instead as the index to write the 0 byte to.

  • Related