0

So, I'm just trying to figure out exactly how malloc works. Here's the code I'm using to test.

  char* line2;

  line2 = malloc(4*sizeof(char));
  fgets(line2,100,stdin);
  printf("%s\n",line2);

So, I'm initializing the line to what I believe is a size of 4. Then I'm using fgets to put 99 characters in my line2. I was expecting that to crash since I was under the impression that the array set by malloc pointed by line 2 has a size of 4. However, when I input a string with more than 4 characters I get that same string. How is that happening?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Jose A
  • 31
  • 6
  • 1
    going off the end of an array is *undefined behaviour* which is not necessarily a crash – M.M May 21 '17 at 07:30
  • Line2 does point to the first of 4 allocated bytes. The fgets() is using the memory after that which was allocated (reserved) by malloc. That memory is apparently available to your program. if it was outside your program's address space, the program would crash as the operating system would not allow it to access memory outside of what it has been authorized.. – Scooter May 21 '17 at 07:40
  • so fgets is changing the size of line2? I guess that was my main concern cause I want to be able to know what's going on with my string as I'm working on a program. – Jose A May 21 '17 at 08:20

0 Answers0