1

C noob here. What does it matter what argument I give malloc when I can pass whatever size string to it later?

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

int main() {
    char *str;
    str = malloc(1*sizeof(char));
    strcpy(str, "abcd");
    printf(str);
    printf("\n");

    return 0;
}

This works fine. I would have thought I wouldn't be able to store more than 1 char in str from my understanding of what malloc is supposed to be.

  • 4
    C has no bounds checking. Writing out of bounds leads to *undefined behavior*. – Some programmer dude Dec 02 '16 at 14:05
  • Try writing, say, 1MB worth of characters to that 1 byte allocation. Your program will crash. – eddiem Dec 02 '16 at 14:07
  • 1
    It matters because you don't want to access memory that is not allocated. This is an undefined behavior and it may or may not crash. The strcpy doesn't know or care how much memory you have allocated. It starts from the first pointer and copies as long as there is something to copy. – Olayinka Dec 02 '16 at 14:08
  • " I wouldn't be able to store more than 1 char in str" --> Curious, what did you except would happen? did you expect the code to stop and error out with a message? – chux - Reinstate Monica Dec 02 '16 at 15:58

1 Answers1

4

malloc can end up actually allocating more than expected to maintain alignment/simplify the allocator.

What you're doing is undefined behavior, and among other things, "undefined" can mean "works, sometimes". Don't do this though, because the other options are not nearly so good. Some of the time, it will crash. Some of the time, it will appear to work, but it turns out you corrupted the heap, and at some later point, using or freeing some completely different allocation, you'll get "inexplicable" data or heap corruption related errors that aren't tied to the overflow in any obvious way.

It's a terrible idea, never rely on having even one byte more than you requested.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271