Thread: Declaring an array's size using a variable causes program to crash

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    2

    Declaring an array's size using a variable causes program to crash

    Hi all,

    I am new to C. I've been trying to use C to code some statistical functions originally coded in R. I've encountered an interesting phenomenon. In the function foo1, I declared the array v1v2b using an actual value 1999000. The function runs fine when I call it in R.

    Code:
    void foo1(double *x, double *y, int *nsamp){
        int i, j, k, oper=2, l;
        double* v1v2=malloc(sizeof(double)*((*nsamp)*(*nsamp-1)/2 + 1));
    
    
        outer_pos(x, y, nsamp, &v1v2[0]);
        double v1v2b[1999000];      //<-------HERE
        for(i=1; i<= 1999000]; i++){
            v1v2b[i-1]=1;
        }
    }

    However, in foo2, I first create an integer variable called index, and store the value 1999000 in it. I then use it to initialize the same array. When I tried calling this function in R, it either led to a stack overflow error, or completely crashed R. I wonder what the problem is. Thanks in advance!

    Code:
    void foo2(double *x, double *y, int *nsamp){
        int i, j, k, oper=2, l;
        double* v1v2=malloc(sizeof(double)*((*nsamp)*(*nsamp-1)/2 + 1));
    
        outer_pos(x, y, nsamp, &v1v2[0]);
        int index=1999000;
        double v1v2b[index];   // <-----------HERE
        for(i=1; i<= index; i++){
            v1v2b[i-1]=1;
        }
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Sorry, false alarm
    Devoted my life to programming...

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    But he has i-1 in the index of the array, so I think he or she is ok
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    If variable-length arrays are actually allowed by your compiler, then I would say you're allocating way too much memory on the stack. You should either use dynamic allocation using malloc/calloc or make this variable static.

  5. #5
    Registered User
    Join Date
    May 2013
    Posts
    2
    I did try using malloc, and got the same error. I think my compiler allows variable-sized arrays. It works elsewhere...just not here...

    Also if too much memory on the stack is a problem, why is it that declaring an array using a number causes no problem - even though the the number is the same as the value stored in the variable?

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The compiler only checks that the array declaration is syntactically correct. It is only when the program is run that the host system environment determines it cannot create the array.

    Practically, if you want really large arrays, you are usually better off using dynamic memory allocation (eg malloc()) rather than just declaring an array of that size. There are all sorts of historical and practical reasons why this is so.


    I do suggest you think carefully about whether such arrays are really needed. Sometimes they are, but most people who use such large arrays could get away with a smaller array and some clever logic to achieve the same intended effect.

    There are three other problems in your code.

    1) Array indices start at zero in C. If an array has 20 elements, it is invalid to access element number 20. Valid indices run from 0 to 19. Your loops have such an "off by one" error. That is a common cause of program crashes.

    2) It is not guaranteed that an int variable can even store the value 1999000. That gives all sorts of potential problems if you attempt to iterate an int from 1 to 1999000.

    3) malloc() can fail. It returns NULL if it does - and it is more likely to do so when allocating large arrays. Attempting to use memory that has not successfully been allocated usually gives a program crash.

    The compiler is not required (in fact, there real-world circumstances where it simply can't) detect such problems. It is the programmers responsibility to avoid them, not for the compiler to detect them.
    Last edited by grumpy; 05-10-2013 at 05:48 PM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > I did try using malloc, and got the same error. I think my compiler allows variable-sized arrays. It works elsewhere...just not here...
    Since there is nothing obviously wrong with your use of v1v2b, suspicion falls on to
    Code:
        double* v1v2=malloc(sizeof(double)*((*nsamp)*(*nsamp-1)/2 + 1));
        outer_pos(x, y, nsamp, &v1v2[0]);
    Now if you don't allocate enough memory for v1v2 (you have a complicated size, is it right?), then this could very easily trash memory and you would never know it.
    The first real opportunity you get to discover whether v1v2 was trashed is on the next call to malloc/free.

    > Also if too much memory on the stack is a problem, why is it that declaring an array using a number causes no problem - even though the the number is the same as the value stored in the variable?
    The compiler is free to call malloc behind the scenes.

    As an array, your 2M array of doubles would have taken 16MB of stack space.
    The default allocation on most desktop systems is somewhere between 1MB and 8MB.
    So yes, this was instant stack overflow.
    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.

  8. #8
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    If you want a local array to be located in the heap instead of the stack, use static:

    Code:
    static double v1v2b[1999000];

  9. #9
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by rcgldr View Post
    If you want a local array to be located in the heap instead of the stack, use static:

    Code:
    static double v1v2b[1999000];
    Post #4 has suggested the use of a static variable. It's no good to have duplicate posts. Read the thread before you post next time
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Hè Xi View Post
    I did try using malloc, and got the same error.
    That's cause you still have the large local array there as well.
    If you use only malloc and remove the large local array, then I you will not get a stack overflow in this function.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Declaring one more variable crashes program.
    By Konstantinos in forum C Programming
    Replies: 9
    Last Post: 12-19-2012, 10:32 AM
  2. Problem in declaring array size inside a function
    By dpitz in forum C Programming
    Replies: 14
    Last Post: 04-27-2012, 04:17 PM
  3. Declaring a variable size char
    By Niara in forum C Programming
    Replies: 11
    Last Post: 10-21-2006, 01:48 AM
  4. help on variable size array
    By 1qaz1234 in forum C++ Programming
    Replies: 7
    Last Post: 02-23-2005, 12:02 PM
  5. help with declaring array in which the user specifies size
    By ibanezrgking in forum C++ Programming
    Replies: 3
    Last Post: 02-10-2002, 10:05 AM

Tags for this Thread