0

I'm creating an array with malloc like so:

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

void main(){
    int * m = malloc(3 * sizeof(int));
    int i;
    m[0] = 1;
    m[1] = 2;
    m[2] = 3;

    for (i = 0; i < 20; i++){
        printf("%d \n", m[i]);
    }

    getchar();
}

As you can see the array should be the size of three integers.

I define the first three elements and then print out 20 elements from the array. but how is this possible? if malloc allocated three integers worth of memory to the array then why does the array still contain additional data past the initial three elements? maybe i am misunderstanding how malloc works, in which case how can i define an array with a strict size that will not include random data which I did not add to it?

thanks

H3XXX
  • 595
  • 1
  • 9
  • 22
  • 2
    C is a low-level language designed for speed. It doesn't hold your hand or waste time with things like array bounds checking--you have to do that yourself. C is perfectly happy to let you do stupid things and shoot yourself in the foot. – Lee Daniel Crocker Oct 11 '18 at 17:48
  • C have no bounds-checking. If you go out of bounds you will have [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) and a plague of [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude Oct 11 '18 at 17:49

0 Answers0