'malloc' and 'Segmentation fault'

Language/C&C++ 2014.07.25 15:39

'Segmentation fault' is very familiar error for C developer.

Then, when this runtime error is issued?

At the moment of accessing not-allocated-memory?

This may be right, but this is NOT strict enough.

'Segmentation fault' is issued by kernel through signal to notify that,

"You - user process - try to access not-permitted memory area. And usually, this happens when it tries to access not-allocated-memory - for the user process (In case of ARM architecture, it is triggered by Data Abort cpu exception).

Let's see below code.

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

main(int argc, const char *argv[]) {
        int i = 0;
        char *s = malloc(1);
        s += 1;
        for (i = 0; i < 1024 * 1024 * 1024; i++) {
                printf("%d\n", i);
                s[i] = 4;
        return 0;

Do you think when this process is stopped by 'Segmentation fault' signal?

"i == 0" ? (that is at the first moment of trying to access not-allocated-memory-by-malloc).

It, is totally up to malloc implementation.

But, at above case, this is definitely NO.

The reason is, kernel(linux) allocate memory for user process at least 1-page.

So, above code will run even if i > 1024 especially on the Linux machine.

And, there are various implementation(algorithm) of malloc.

So, we cannot expect exact value of i for above code.

Important thing to know here is, answer the question - "What exactly does 'Segmentation fault' mean?"

'Language > C&C++' 카테고리의 다른 글

[C/C++] sizeof array  (0) 2015.03.19
[Macro] '##' macro operator  (0) 2015.02.11
'malloc' and 'Segmentation fault'  (0) 2014.07.25
[GCC] Initialize array...  (0) 2014.07.25
[Linux] Using named pipe in linux (주의할 점)  (0) 2014.01.09
[c/c++] file copy using 'sendfile' on linux.  (0) 2013.12.17
Trackback 0 : Comment 0