Seg Fault in different places

This is a discussion on Seg Fault in different places within the C Programming forums, part of the General Programming Boards category; Hi, I have some code with a large 3d array. I'm trying to run this on a server running linux ...

  1. #1
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18

    Exclamation Seg Fault in different places

    Hi,
    I have some code with a large 3d array. I'm trying to run this on a server running linux because I will get more memory than my pc (24gb RAM). When I run it on the server, I get a segfault right before an input, when I put zeros into the array:

    Code:
     Maximum Spacings 66    Number of bins: 660
    
    Program received signal SIGSEGV, Segmentation fault.
    0x0000000000400f62 in main () at triplet.c:108
    108                 for(k=0;k<91;k++)density3[i][j][k]=0;
    where int density3[660][660][91];

    When I run this locally it also segfaults. However, when I use gdb locally, it segfaults a little bit after this code, after I've input something in.

    Code:
    Program received signal SIGSEGV, Segmentation fault.
    0x00401a71 in main () at Z:\VortexStuff\Triplet\fileTriplet.c:162
    162                 k=density3[r_rA][r_rB][i];k++;probCounter++;
    
    160-164
    for(i=0;i<91;i++)
                {
                k=density3[r_rA][r_rB][i];k++;probCounter++;
                density3[r_rA][r_rB][i]=k;
                }
    I would have expected that the server had faulted later, if not at all, especially given the larger address size.

    Theoretically, the server would have the necessary amount of space in order for me to make the array I need.
    My program is nearly 1000 lines, so I'd rather not post the whole thing. I take several inputs and write to a file many times in the end. Thanks

  2. #2
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,189
    Post the relevant code showing the declaration, allocation and operation that is causing the crash.

    Also, try to clean it up, since that code is not very readable. It is considered bad coding style to do things like

    Code:
    k=density3[r_rA][r_rB][i];k++;probCounter++;
    on a single line, specifically because when you get an error, its impossible to tell which of the 3 commands caused it. I woudl hazard a guess that you are overrunning your array limits.

    Try rewritign that as
    Code:
    k=density3[r_rA][r_rB][i];
    k++;
    probCounter++;
    Last edited by abachler; 07-01-2008 at 01:31 PM.
    Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    If you have
    Code:
    int main ( ) {
        int density3[660][660][91];

    Consider
    Code:
    int main ( ) {
        static int density3[660][660][91];
    Most machines limit the amout of stack space compared to the amount of memory for global / static / heap data.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18

    Cleaner code

    Okay, I managed to get a stack overflow locally, which means that the program is working correctly (hopefully).

    here's the error I get on the server, and I'm not sure exactly why:
    Code:
    Assignment and creation:
    binSize = 10*rint(maxr/latconst);
          printf("\n Maximum Spacings %d\tNumber of bins: %d\n",binSize/10,binSize);
           //if the lattice spacing interval is within acceptable limits
             
          int density3[binSize][binSize][91],rA,rB,theta; //180 degrees(by two) and .1* a0
          //initialize array
          for(i=0;i<binSize;i++)
             for(j=0;j<binSize;j++)
                for(k=0;k<91;k++)
                   density3[i][j][k]=0; //## SEG FAULT HERE!!
    Not sure what's up. Would I be going out of bounds or something?
    here's the segfault itself:
    Code:
     Maximum Spacings 66    Number of bins: 660
    
    Program received signal SIGSEGV, Segmentation fault.
    0x0000000000400f62 in main () at triplet.c:109
    109                    density3[i][j][k]=0;

  5. #5
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18
    if I made it static, I take it I'd have to hard code it's size?

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    You should have to do that anyway.
    If you require dynamic size, you should be using malloc/free instead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    > if I made it static, I take it I'd have to hard code it's size?
    Why do I get the feeling there's a whole bunch of stuff you're not telling us. This isn't the psychic programmers network.

    No matter how many 1000's of lines long the code is, if it's crashing at the first initialisation loop, you can delete EVERYTHING which executes after the loop and just post what remains.
    Create a copy of your project to test these ideas on, without the clutter of the rest of the program.

    Hopefully, you'll have say 50 lines which crashes and you can simply copy/paste for us to look at and tell you a real answer right off the bat!
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18

    Post More Code

    Here's the code before it segfaults:
    Code:
    //Tester file to deal with segFault
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string.h>
    #include <time.h>
    
    #define CORRPHI0 2070000.0
    #define CORRVLNUM 40000 
    #define VLMAX 41000
    
       char *fileDefine(char *name);
       //void generatePlotFile(char *name,int size);
    
       int main(void)
          {
          int corrvlnum, i, j, k, r, z, isLevel, lcheck,probCounter=0,sample,debug=0;
       
          double ax, ay, bx, by, tx, ty, maxr,latconst, field=0.0,t0,dT,\
    absMaxX, absMinX, absMaxY, absMinY;
          double vlinit[2][VLMAX];
          FILE *fp;
          char *theFile;
       
          int fdebug;
       
          printf("Generate a Correlated Points list?\n1. Yes\n0. No\n");
          scanf("%d",&fdebug);
       
          if(fdebug)
             {
             theFile = fileDefine("Correlated Points");
             fp = fopen(theFile, "w"); //Writing to the file
          
             if (fp == NULL)
                {
                printf("Error Opening File!");
                return 1;
                };
             }
       
          while (field == 0.0)
             {printf("Enter magnetic field(mT):\n");
             scanf("%lf",&field);}
       
          //starts the timer
          t0=(double)time(NULL);
          //printf("Start Time: %lf Seconds\n",t0);
       
          vlinit[0][0] = vlinit[1][0] = 0.0;
          latconst = sqrt(CORRPHI0 * 2.0 / (sqrt(3.0) * field));
          // real lattice vectors
          ax = 0.5 * latconst;
          ay = sqrt(3.0) * latconst / 2.0;
          bx = latconst;
          by = 0.0;
          printf("Field %lf mT; a0 %lf nm\n", field, latconst);
          if(fdebug) fprintf(fp,"#Field %lf mT; a0 %lf nm\n", field, latconst);
       
          maxr = sqrt(sqrt(3.0) * ((double) CORRVLNUM) / (2.0 * M_PI));
       
          z=0;
          for (i=-2*maxr; i<=2*maxr; i++)
             for (j=-2*maxr; j<=2*maxr; j++) {
                tx = i * ax + j * bx;
                ty = i * ay + j * by;
                if (tx*tx + ty*ty < maxr*maxr*latconst*latconst) {
                   vlinit[0][z] = tx;
                   vlinit[1][z] = ty;
                   z++;
                   if(tx==0 && ty==0 && debug)printf("%lf\t%lf\n",tx,ty);
                
                   if(tx<absMinX) absMinX=tx;//find minimum and maximum in set
                   else if (tx>absMaxX) absMaxX=tx;
                   if(ty<absMinY) absMinY=ty;
                   else if (ty >absMaxY) absMaxY=ty;
                   }
                }
          corrvlnum=z;//check vlnum
          printf("Initial lattice for correlation functions fills circle with %d vortex lines.\n\n",corrvlnum);
          if(fdebug) fprintf(fp,"#%d Vortex Lines.\n",corrvlnum);
       
          int r_rA,r_rB,r_theta,binSize =1001;
          maxr = absMaxX-absMinX > absMaxY-absMinY ? absMaxX-absMinX: absMaxY-absMinY;
          binSize = 10*rint(maxr/latconst);
          printf("\n Maximum Spacings %d\tNumber of bins: %d\n",binSize/10,binSize);
              
          static int density3[1001][1001][181],rA,rB,theta; //180 degrees and .1* a0
          //initialize array
          for(i=0;i<binSize;i++)
             for(j=0;j<binSize;j++)
                for(k=0;k<181;k++)
                   density3[i][j][k]=0; //--> SegFaults here
          }
       char *fileDefine(char *name)
          {
          char *input = malloc(50);
          printf("Enter %s File Name:\n",name);
          scanf("%49s",input);
          return input;
          }

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    if(tx<absMinX) absMinX=tx;//find minimum and maximum in set
    absMinX used without being initialized.
    if(ty<absMinY) absMinY=ty;
    absMinY used without being initialized.
    else if (tx>absMaxX) absMaxX=tx;
    absMaxX used without being initialized.
    else if (ty >absMaxY) absMaxY=ty;
    absMaxY used without being initialized.

    Aside from that, when fixed, I don't get any seg faults.
    Last edited by Elysia; 07-02-2008 at 08:25 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18
    okay, thanks guys. I also managed to find out that the maximum size of a static array is somewhere around 181*1711*1711*sizeof(int). Unfortunately it may be too small. Oh well, I'll figure something out (maybe another static array, we'll see)

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    That's 2 GB. Seriously, you need to cut down on memory usage.
    You've hit the upper limit for a 32-bit application (at least on Windows).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18
    Linux Server w/ 24gb ram. I think I'll be okay

  13. #13
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    But do you really need that much memory?

    Here's one idea: spreadsheet programs don't generally store the spreadsheet in an array-like structure. That would mean, if you inserted an element at 0,0 and another at 1000,1000 that it would need to allocate 1000x1000 cells, where only two are used. Instead, they might use a scheme like this: for each cell, allocate the data for the cell, and the position it is located. In other words:
    Code:
    struct cell {
        void *data;
        int x, y;
    };
    
    struct spreadsheet {
        struct cell *cell;
        size_t cells;
    };
    Then you only need to allocate two cells. Of course, each cell is a bit bigger, since you have to store the position in the cell; but if you have a sparse scattering of cells, it's likely to be more memory efficient.

    On another note, there are better ways to store the cells than in one big list like that. You might have a trie of sorts, for example.
    Code:
    struct column {
        struct cell *cell;  /* these are kept in order */
        size_t cells;
    };
    
    struct spreadsheet {
        struct column *row;
        size_t width;
    };
    If you made spreadsheet->row into a trie, you'd allocate enough space so that you could use spreadsheet->row[x] directly instead of searching through the list of rows. (Note that this is assuming that most rows have some data in them . . . .)

    Code:
          static int density3[1001][1001][181],rA,rB,theta; //180 degrees and .1* a0
          //initialize array
          for(i=0;i<binSize;i++)
             for(j=0;j<binSize;j++)
                for(k=0;k<181;k++)
                   density3[i][j][k]=0; //--> SegFaults here
    Note: you can initialize an array to all zeros like this:
    Code:
    char array[1][2][3] = {{{0}}};
    But static (and global) arrays are automatically initialized to zeros.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting a seg fault
    By ammochck21 in forum C Programming
    Replies: 11
    Last Post: 01-23-2009, 04:27 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21