I've created a simple program that has a struct node that consists of only an int id. In main(), I've created a node pointer array, and used malloc(sizeof(struct node)*3) to allocate space for three struct node. I then make these three pointers point to the nodes first, second, and third.
However, I also create a fourth and fifth node, and allocate these to pointers after the third node. I was expecting to get a segmentation fault, but instead the program successfully reads and prints the int id for fourth and fifth, despite the fact that I didn't allocate memory.
Am I misunderstanding malloc()? Also, if we are treating a pointer like an array, is there any way to get the number of elements on that array?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
struct node{
int id;
};
int main(){
struct node * array;
array = malloc(sizeof(struct node) * 3);
struct node first = {7};
struct node second = {8};
struct node third = {9};
struct node fourth = {10};
struct node fifth = {11};
*(array + 0) = first;
*(array + 1) = second;
*(array + 2) = third;
*(array + 3) = fourth;
*(array + 4) = fifth;
printf("%d, %d, %d, %d, %d\n", (array + 0) -> id, (array + 1) -> id, (array + 2) -> id, (array + 3) -> id, (array + 4) -> id);
printf("%d\n", sizeof(array));
}