0

The following code prints all the numbers between 1 and 300. How come it does not throw throw a segmentation fault?

Compiled with:gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

Also this is now different from malloc(0) actually works?

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
  int *pi = (int *)malloc(1);
  int i = 0;
  for(i = 0;i < 300;i++) {
    *(pi + i) = i + 1;
  }
  for (i=0;i < 300;i++) {
    printf("%d\n", *(pi + i));
  }
  return 0;
}
Community
  • 1
  • 1

1 Answers1

1

malloc(0) is implementation defined and returns either a null pointer or a pointer that must not be dereferenced.

Dereferencing the result of malloc(0) invokes undefined behavior.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • malloc(1) also works. – user3004771 May 24 '14 at 11:59
  • @user3004771 that is because the allocator usually gives your the smallest block it can work with, and that can be way more that 1 byte. – Erbureth May 24 '14 at 12:00
  • It works even with 400 integers. – user3004771 May 24 '14 at 12:04
  • page size in x86 is 4 kB – Erbureth May 24 '14 at 12:06
  • So if i ask for a byte, malloc returns at least 4kB?That seems like a waist.Indeed, it seems to work until 4000. – user3004771 May 24 '14 at 12:12
  • 1
    What malloc allocates is completely implementation-defined. However you can still get past that memory and it will not generate segmentation fault unless you cross the page boundary to cpu-unallocated region. – Erbureth May 24 '14 at 12:15
  • @user3004771 *undefined behavior*: It can crash or not. Or crash tomorrow or do whatever. – ouah May 24 '14 at 12:36
  • @ouah:So malloc retuns random-sized chunks of memory?I do not believe that. – user3004771 May 24 '14 at 12:48
  • 1
    @user3004771 *(C99, 7.20.3p1) "If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object."* – ouah May 24 '14 at 12:53
  • 1
    @user3004771: `malloc` formally allocates **exactly** what you ask for, and it formally returns a pointer to a memory block of that size. If it **really** allocates a few bytes more, that is incidential. The fact that your program does not immediately crash if you do something different because the hardware uses 4k pages and thus cannot detect your illegal use of memory at a granularity of a few bytes is circumstantial. – Damon May 24 '14 at 16:18
  • so malloc allocates at least what i ask for, but the difference is less than the cpu's page size? – user3004771 May 24 '14 at 16:33