1

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));
}
NukPan
  • 249
  • 2
  • 8

1 Answers1

3

What you are seeing is Undefined Behaviour at it's most confusing: things work that shouldn't work.

When you use malloc to allocate a block of memory of a given size (let's say, 20 bytes), there is no constraint on the implementation to allocate exactly that amount. In fact, on most modern PCs and operating systems, memory is more efficiently allocated in fixed-size blocks rather larger than 20 bytes, and typically something like 512 or 1,024 bytes (often known as a memory page).

Thus, it would appear in your case that this has happened - but NEVER rely on this working. In fact, you may run your program 1,000 times and it works but, on run number 1,001 it doesn't work.

Also, if we are treating a pointer like an array, is there any way to get the number of elements on that array?

Short answer: No! When you use malloc to reserve memory, it is down to you to make sure you stay within the allocated bounds.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Thanks a million for your answer! – NukPan Nov 12 '19 at 21:31
  • The behavior in the question is not evidence that `malloc` allocated more than the requested amount of memory. The fact that the program can write to it and read from it just means the memory is mapped and writeable. It could have been memory that was allocated to something else, memory that the memory management subsystem had acquired from the operating system but not yet allocated, data structures used by the memory management subsystem, or other things. – Eric Postpischil Nov 12 '19 at 22:00