Why Segmentation Fault?

Discussion in 'C' started by coderzone, Jan 25, 2011.

  1. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    38
    Trophy Points:
    28
    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.
     
  2. jimblumberg

    jimblumberg New Member

    Joined:
    May 30, 2010
    Messages:
    120
    Likes Received:
    29
    Trophy Points:
    0
    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
     
  3. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    38
    Trophy Points:
    28
    32 Bit WinXP and MS Visual Studio 2005
     
  4. jimblumberg

    jimblumberg New Member

    Joined:
    May 30, 2010
    Messages:
    120
    Likes Received:
    29
    Trophy Points:
    0
    What does numeric_limits<int>::max() return?

    I get 2147483647.

    Note: You must #include <limits>


    Jim
     
    shabbir likes this.
  5. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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 likes this.
  6. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Well Said.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice