0

Test Case: I want to allocate memory using realloc() on an int array. I allocate memory for 2 values, but if I write the third value and so on to the array, they are also written and displayed. Why am I not getting a SegFault error?

P.s Exactly the same problem when using malloc()

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

typedef struct Test
{
    int *nums;
} Test;

int main()
{
    Test test;

    test.nums = NULL;
    test.nums = realloc(test.nums, 2 * sizeof(int));

    test.nums[0] = 1;
    test.nums[1] = 2;
    test.nums[2] = 3;
    test.nums[3] = 4;
    test.nums[4] = 5;
        
    printf("%d %d %d %d %d\n", test.nums[0], test.nums[1], test.nums[2], test.nums[3], test.nums[4]);

    free(test.nums);

    return 0;
}

enter image description here

  • 1
    Accessing beyond allocated memory is Undefined Behavior (UB). This means that anything can happen. You *may* get a SegFault, or not. Detecting this would require more instructions to be executed every time you access the pointer, leading to slower code. If you are not sure if the index will be inside the allocated memory, write a check yourself. – Costantino Grana Oct 15 '22 at 17:43
  • C doesn't provide training wheels. If you access memory out of bounds it might crash, corrupt something else, or even appear to work fine, but it's always a bug. – Retired Ninja Oct 15 '22 at 17:44
  • But you can enable static code analysis, which would definitely detect your specific example of accessing beyond allocated memory boundaries. – Costantino Grana Oct 15 '22 at 17:46
  • "_Why am I not getting a SegFault error?_" Because you have not yet encroached upon a segment that is not mapped you your process. Overrunning a memory allocation is "undefined behaviour" with respect to the C language definition. C performs no bounds checking, it certainly does not guarantee a seg-fault or any kind of exception. That behaviour is provided by the execution environment (the OS andvMMU hardware). – Clifford Oct 15 '22 at 17:52
  • 2
    To flag this in realtime, compile with `-fsanitize=address`. It will catch even going over bounds by even a single byte in most cases. – Craig Estey Oct 15 '22 at 17:52

0 Answers0