Pratik Singhal
Pratik Singhal

Reputation: 6492

Can segmentation fault be caused by exhaustion of memory ?

I am solving a problem on codechef.

I have coded the algorithm of the problem and it runs fine on the test cases. Although, when I run it on codechef(online), it throws segmentation fault.

I have double checked that, I am not accessing any inaccessible memory locations, although I suspect that my program could have taken up huge amount of memory.

So, my question is that Can segmentation fault be thrown, when there is no more memory available for the program to execute. Something like OutOfMemoryException in C#

Upvotes: 2

Views: 4804

Answers (3)

Scis
Scis

Reputation: 2984

As Kerrek mentioned in the comments an excessive usage of automatic storage or a call stack which is too deep can cause a SEG-fault e.g (on coliru):

void foo(){ foo(); }

int main() {
    foo();
    return 0;
}

or (on coliru):

#include <iostream>
int main()
{
    int a[50000000];        
    std::cout << a[500];    
}

So to sum it up you have to be aware of your systems limitations, for example some recursive brute force solutions are sometimes theoretically OK and should work but are rather impractical (yes, this is a vague example but the OP did not mention what problem is being solved nor how so I wanted to give the above at least some context...).

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

There are actually two situations

1. You try to allocate too much from the call stack, then you'll receive a signal. An exception can't be caught


int main() {
    try {
        std::array<int,10000000> arr;
        cout << arr[40] << endl;
    }
    catch(const std::exception& e) {
        cout << e.what() << endl;
    }
    return 0;
}

2. You try to allocate too much dynamic memory, then you'll receive an exception


int main() {
    try {
        std::vector<int> arr;
        arr.resize(1000000000);
        cout << arr[40] << endl;
    }
    catch(const std::exception& e) {
        cout << e.what() << endl;
    }
    return 0;
}

You can try it live on ideone.

Upvotes: 0

dragonroot
dragonroot

Reputation: 5821

This depends on the way you allocate memory and whether you check for errors when doing so. E.g. malloc would return NULL on an out-of-memory condition. A failure to check that may lead to dereferencing NULL which would result in a segmentation fault. If you use new of C++, it would throw an exception instead.

In reality though when a program does excessive memory allocations it usually gets the system RAM overcommitted and its process is killed by an OOM killer before its malloc would start returning NULLs - unless most of the allocated memory is actually unused.

Upvotes: 1

Related Questions