2

I have a simple question which I don't seem to be able to find an answer to anywhere.

Why does this code compile and work when i allocated enough memory for just two characters, "he", "hellos" shouldnt be able to fit?

It prints out correct length, which is 6.

The free gives no error.

char* testF() {
    char *arr = (char*)malloc(2*sizeof(char));
    strcpy(arr, "hellos");
    return arr;
}

int main() {
    char *arr = testF();
    printf("%c%c%c%c%c%c\n", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]);
    printf("Length = %d", strlen(arr));
    free(arr);

    return 0;
}
Ludvig W
  • 744
  • 8
  • 27

3 Answers3

2

Why does this code compile and work when i allocated enough memory for just two characters, "he", "hellos" shouldnt be able to fit?

It's undefined behaviour because strcpy() call overflows the buffer.

The C standard doesn't require an implementation to give error or warnings on undefined behaviours. So, you can't expect anything to save you; you are on your own.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Should I change the malloc to char **arr = (char*)malloc(6*sizeof(char)); or char **arr = (char*)malloc(7*sizeof(char)); to properly store it? – Ludvig W Jan 15 '17 at 19:08
  • It must be `7` bytes, including the null byte termination. So, the latter. You should also check the return value of `malloc()` to see if it's failed: `if (arr == NULL) { perror("malloc"); exit(EXIT_FAILURE);}`. – P.P Jan 15 '17 at 19:09
  • 1
    @Lurr `*arr = malloc(7 * sizeof(*arr));` would now probably be the best thing to use. Thanks for pointing that out. – cs95 Jan 15 '17 at 19:27
1

This can happen, if there is free memory after the area which was allocated by malloc.

But of course you must count on it. Trust only what you allocate.

Actually this is a source for nasty bugs, because some bad code like mallocing insufficient memory or using deallocated memory can work. And then one day you make a small change that affects the memory scheme, or update a compiler version, and things start to crash...

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
  • So basically, IF I'm unlucky in a bigger program that I write stuff on the memory where the rest, "llos" of "hellos" is saved, I would get a crash when accessing it? Or bad values? @designerman – Ludvig W Jan 15 '17 at 19:10
  • 1
    If you are unlucky enough, there won't be any crash for a time, and after you change something, there will be... – Israel Unterman Jan 15 '17 at 19:22
1

The only reason you get no error is because the amount of data you copy can still fit within the memory page. If you were to, by chance copy data that resulted in a page overflow, you'd get a SIGSEGV (segmentation) error.

In conclusion, this is undefined behaviour.

cs95
  • 379,657
  • 97
  • 704
  • 746