Mike Mouawad Mike Mouawad - 3 months ago 15
C++ Question

c++ - string of 64 ASCII characters overflows malloc(64 * sizeof(char))

The below code throws an error if I provide a string that is 64 characters long of hexadecimals (ie: 26C8D8AB82B027808A371BC46EA789364AB8419F2B17EADFE955CBE5C6369011), even though I allocated 64 * sizeof(char) bytes for it which should be enough:

char* username = (char*)malloc(64 * sizeof(char));
std::cin >> username;
free(username);


The error is thrown in the third line when I free the allocated memory:


CRT detected that the application wrote to memory after end of heap
buffer.


This does not happen with 63 characters or less. Can anyone tell me why exactly 64 * sizeof(char) is not enough and why is the error thrown when freeing the memory not before ...

Answer

C strings are NULL-terminated.

You did not leave space for the terminator.

The error is detected when freeing the memory, because that's the function that looked at the padding after the object and found it was corrupted. If you disable memory debugging, there might not be any checking (possibly even no padding) and this sort of error could go undetected until it trashes a completely unrelated piece of data.

If you know the exact length already and don't need a terminator to mark the end, you can use

cin.read(username, 64);

This will not store a terminator, and also won't ever read more (or less) than 64 characters of input, so it will not overflow.

Comments