Reputation: 2488
I have the following test-code compiled on Win7's MinGW's gcc using C::B:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Func. prototype */
char* returnString (void *str);
int main()
{
printf("%s", returnString("Hello World!!!!!!!!!!!!"));
return 1;
}
char* returnString (void *str)
{
char *local = malloc(strlen((char*)str));
strcpy(local, (char*)str);
return local;
}
By default the allocation would cause a leak/u/b.. because i have to allocate one free byte +1
where the null terminator would be located. But instead of causing a leak or crash it works like null-terminated. Is there any way to dissable this?
..instead of going through 5543 lines of code where +1
is used.
Upvotes: 2
Views: 131
Reputation: 80255
The line below causes a buffer overflow because of the missing + 1
when the size to allocate was previously computed.
strcpy(local, (char*)str);
A buffer overflow is much more serious than a memory leak. Unfortunately, a buffer overflow does not systematically crashes the program. It invokes undefined behavior, meaning that anything can happen, including the program continuing as if you had allocated a large enough bloc. This is not a compiler optimization: it can happen (or not) at any optimization level, and the programmer has very little control over what happens. See below for some partial solutions.
One way to obtain diagnostic messages for many buffer overflows is to use Valgrind to execute the program after having compiled it normally.
Alternately, recent versions of Clang and GCC incorporate an “address sanitizer” feature, activated with -fsanitize=address
, that inserts in the generated code some instructions that may detect the problem. I haven't used this feature but documentation is available.
Upvotes: 5