Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Why Segmentation Fault? (http://www.go4expert.com/forums/why-segmentation-fault-t24729/)

coderzone 25Jan2011 19:40

Why Segmentation Fault?
 
Why a segmentation fault?
Code:

#include <iostream>
#include <new>
using namespace std;
struct AB {
        int A;
        int B;
};


int main(void) {
        int llength;
        llength=1111111111;
        AB *L;
        L= new AB[llength];
        L[37370197].B=-37370197;
        delete [] L;
        return 0;
}

I think it should be out of memory.

jimblumberg 25Jan2011 20:32

Re: Why Segmentation Fault?
 
The above code compiled and ran for me with no errors. Or segmentation faults.

What compiler and operating system are you using? What is your maximum size of an int?

I am using g++ on Linux.


Jim

coderzone 25Jan2011 20:54

Re: Why Segmentation Fault?
 
32 Bit WinXP and MS Visual Studio 2005

jimblumberg 25Jan2011 21:09

Re: Why Segmentation Fault?
 
What does numeric_limits<int>::max() return?

I get 2147483647.

Note: You must #include <limits>


Jim

xpi0t0s 26Jan2011 12:28

Re: Why Segmentation Fault?
 
Quote:

Originally Posted by coderzone (Post 78254)
32 Bit WinXP and MS Visual Studio 2005

That probably explains it. You're allocating 1111111111 pairs of 4-byte ints, that's 2,222,222,222 ints and of course 2,222,222,222*8 bytes (16.55GB), which is way over the maximum 3.2GB limit of 32-bit systems. If you want to write code like that, you're going to have to upgrade to 64-bit, or find some other way around it like using sparse arrays or a disk file.

If C were "nice", yes, you should get an "out of memory" error. But C isn't nice; it assumes you know what you're doing and only falls over when it really has to.

shabbir 26Jan2011 14:23

Re: Why Segmentation Fault?
 
Quote:

Originally Posted by xpi0t0s (Post 78275)
If C were "nice", yes, you should get an "out of memory" error. But C isn't nice; it assumes you know what you're doing and only falls over when it really has to.

Well Said.


All times are GMT +5.5. The time now is 06:22.