Kraffs
Kraffs

Reputation: 533

Freeing a character pointer returns error

I'm trying to free a character pointer after having used it but it returns a strange error.

The error says:

_CrtDbgREport: String too long or IO Error

The debugger itself returns no errors while compiling.

The code currently looks like this:

void RespondToUser(SOCKET client, SOCKET server)
{
    char buffer[80];
    char *temp = malloc(_scprintf("HTTP/1.1 200 OK\r\n%s\r\nServer: %s\r\nConnection: close\r\n\r\nHi!", buffer, SERVER_NAME));
    sprintf(temp, "HTTP/1.1 200 OK\r\n%s\r\nServer: %s\r\nConnection: close\r\n\r\nHi!", buffer, SERVER_NAME);

    send(client, temp, strlen(temp), 0);
    closesocket(client);
    free(temp);
    ListenToUsers(server);
}

The problem only occurs when I try to free the temp pointer from the memory and not otherwise. What might be causing this?

Upvotes: 0

Views: 61

Answers (1)

hmjd
hmjd

Reputation: 121971

The call to sprintf() is writing one past the end (as it appends a NULL terminator), as the return value from _scprintf() does not include the NULL terminator. From _scprintf() reference page:

Returns the number of characters that would be generated if the string were to be printed or sent to a file or buffer using the specified formatting codes. The value returned does not include the terminating null character.

This means the program has undefined behaviour. To correct + 1 to _scprintf()s return value.

Upvotes: 1

Related Questions