1

I wrote the following expecting to get a seg fault or garbage output by printf

#include <stdio.h>
#include <stdlib.h>

main(){
    char* test = malloc(1);
    *test = 'a';
    *(test+1) = 'b';
    *(test+2) = 'c';
    *(test+3) = 'd';
    *(test+4) = 'e';
    *(test+5) = 'f';
    printf("%s\n", test);
}

Instead the output was:

 abcdef

I only allocated 1 byte, so why am I allowed to write passed that single byte? Also, how does printf know when the string is terminated? Are all of the bytes that I don't explicitly assign characters to the null-character? I would expect these to be random garbage, yet it seems to terminate at the right spot. I hope this is specific enough! Thanks.

B. Berry
  • 11
  • 1
  • 2
    It is undefined behavior. There is no requirement in the standard to do anything specific. – Retired Ninja Feb 15 '18 at 01:42
  • Usually `malloc` allocates more space than you requested (to be aligned to the next page), thus you can access the memory beyond the requested limit. But there is no guarantee that for that and you shouldn't pass the limit anyway. – Pablo Feb 15 '18 at 01:51
  • I don't know if I should redirect to either page, as they both somewhat answer the question. Seems to be because of paging and then undefined behavior, so my mental model is irrelevant when writing code this nasty. Thank you for the quick responses, by the way. – B. Berry Feb 15 '18 at 01:59
  • The string is null terminated because many `malloc()` implementations ask for pages from the operating system to be zeroed out first. Also, in glibc, the smallest region `malloc()` will consider "allocated" is eight bytes. Any program that relied on that, though, would of course need to know exactly what it is doing! – Whilom Chime Feb 15 '18 at 02:01
  • Thanks, that clears it up nicely. – B. Berry Feb 15 '18 at 02:08
  • @Pablo: It's not aligned to a page (unless you're talking about the underlying request for memory from the OS), but a given allocation is usually at least 8 bytes in size, even if less is requested. Writing beyond that buffer could segfault immediately (if it writes to an unallocated page), or corrupt the heap. But relying on even that is relying on undefined behavior, which will bite you eventually. – ShadowRanger Feb 15 '18 at 02:10
  • From the The C programming by Denis Ritchie _The user can do anything with the space requested, but if anything is written outside of the allocated space the list is likely to be scrambled_ – Achal Feb 15 '18 at 02:17

0 Answers0