To correctly allocate an array using malloc
, use sizeof to determine the size of each element in your array, then multiply by the number of each that you need.
Your code is only allocating 2 bytes of memory in heap, so when you write these integers (which take 4 bytes each on my machine), you are overwriting the values of unrelated state within the heap located beyond those two bytes, thus corrupting the machine state and creating undefined (that's bad) behavior.
In addition, your for
loop was looping on the size of array pointer, which is typically 8 bytes. So your for
loop would have tried to walk over 8 int elements, in an array of 6 ints in which you had only allocated 2 byte instead of the 24 bytes needed. Lots of bad undefined behaviour to go around here!
You may or may not get a segmentation fault due to this. A segmentation fault means you are dereferencing a pointer to an invalid page (segment) of memory, and this is caught by the hardware.
When you corrupt memory, you may not see the result of your error immediately as a segmentation fault if the memory you are writing is valid memory. Worse, if you corrupt the stack or a pointer, it may take a long time to get an actual fault to help detect the corruption created. This makes it hard to connect the fault to the event that caused the exception since your code could run for a long time before getting a segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#define NUM_INTS_WANTED 6
int main(int argc, char* argv[]){
// No more trampling memory since array allocated to correct size
int *array = malloc(sizeof(int)*NUM_INTS_WANTED);
// Always check if malloc succeeded by checking that pointer is not NULL
if (array != NULL) {
array[0] = 2;
array[1] = 1;
array[2] = 3;
array[3] = 4;
array[4] = 4;
array[5] = 6;
// No more seeing 8 ints since you stop after 6 ints now
for(int i = 0; i < NUM_INTS_WANTED; i++){
printf("%d\n",array[i]);
}
} else {
// malloc failed! Report it.
printf("malloc failed!\n");
}
}