Reputation: 20078
My question is why the following code snippet doesn't crash ?
int main(int argc, const char * argv[])
{
const char* source = "SomeText";
char* dest = (char*)malloc(sizeof(char)); // isn't this wrong ?
strcpy(dest, source);
printf("%s\n", dest);
free(dest);
return 0;
}
Upvotes: 0
Views: 112
Reputation: 7482
Behavior in such a case is undefined. In fact a memory outside the reserved place is overwritten. This memory can hold some important information or not. It may be mapped into address space of the process or not. If it is not mapped a system error happens. If it is mapped, then the most probably this memory contains values required for correct working of malloc and free, so you may expect crash on the next malloc or free. If you overwrite a larger part of memory you may write into some other dynamically allocated buffer.
In your case you are overwriting only 8 bytes outside the reserved place. The most probable is that those 8 bytes are mapped into address space and are not used at all. This is why nothing happened. The exact behavior depends on the particular implementation of malloc and free..
Upvotes: 1
Reputation: 9680
strcpy
will overrun the buffer when it is too small to hold the string being copied. This will cause undefined behaviour or even program crash (segfault) because strcpy
will try to write into memory which is not allocated to the buffer. You can't rely on what happens. Next time you run your program, it may very well crash. Here are some fixes I suggest.
// in main
const char *source = "SomeText";
char *dest = malloc(strlen(source) + 1); // +1 for the null byte at the end
if(dest != NULL) { // check for NULL
strcpy(dest, source);
printf("%s\n", dest);
free(dest);
}
else {
printf("not enough memory\n");
}
strlen
doesn't count the null byte in a string, so you have to allocate one extra byte for it to be copied by strcpy
from the source
string. You should check the result of malloc
for null. Also, you should not cast the result of malloc
. There's no benefit and it can lead to bugs if you forget to include the stdlib.h
header file.
Upvotes: 2
Reputation: 60027
Luck?
But usually malloc grabs memory that is convenient for the OS. So maybe it is 1K
Upvotes: 1
Reputation: 43662
Because it is undefined behavior and can happen to work or not. Writing to unallocated space is a risky operation which is not guaranteed to succeed.
Upvotes: 1