Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does running this not issue a segmentation fault? [duplicate]

Tags:

c

memory

malloc

gcc

Possible Duplicate:
Invalid read/write sometimes creates segmentation fault and sometimes does not

I have the following code:

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

int main() {
    int *ptr = NULL;
    ptr = malloc(sizeof(char));
    if (ptr) {
        *ptr = 10;
        printf("sizeof(int): %zu\nsizeof(char): %zu\n", sizeof(int), sizeof(char));
        printf("deref of ptr: %d\n", *ptr);
        free(ptr);
        return EXIT_SUCCESS;
    }
    else
        return EXIT_FAILURE;
}

When I compile and run it, I get following output:

$ gcc test.c
$ ./a.out 
sizeof(int): 4
sizeof(char): 1
deref of ptr: 10

The value sizeof(char) is less than sizeof(int). My malloc call only sets aside enough space for a char. Yet, my program is able to assign an integer value to ptr without crashing. Why does this work?

like image 548
Alex Reynolds Avatar asked Nov 30 '22 15:11

Alex Reynolds


1 Answers

Just because you are writing into unallocated memory does not mean the program will crash. There is no runtime bounds checking like that.

The segfault will occur when you are accessing memory out of the address range allocated through the operating system as detected by the hardware. You may get away with a lot of memory access before then in your heap.

like image 151
Francis Upton IV Avatar answered Dec 04 '22 13:12

Francis Upton IV