Thread: variable length array

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    17

    variable length array

    this code snippet compiles and runs fine

    Code:
    #include <stdio.h>
    
    int main(void) {
            int i, a[i];
    
    
            i=2;
            for(int n=0; n<=i; n++)
                    a[n]=0;
            for(int n=0; n<=i; n++)
                    printf("%i ", a[n]);
            printf("\n");
    
    
            return 0;
    }
    it prints out 3 "0", but when slightly changed

    Code:
    #include <stdio.h>
    
    int main(void) {
            int i, a[i];
    
    
            i=200;
            for(int n=0; n<=i; n++)
                    a[n]=0;
            for(int n=0; n<=i; n++)
                    printf("%i ", a[n]);
            printf("\n");
    
    
            return 0;
    }
    it compiles fine but core dumps when run, how come? i'm using gcc version 4.4.7, and compiling like this

    gcc -std=c99 test.c -o test
    Last edited by brassbin; 11-13-2013 at 02:17 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    > int i, a[i];
    The value in i is garbage when it comes to declaring the array.
    If the value is negative (50% chance), or larger than your stack (99% of all positive numbers), you're screwed.

    > i=200;
    > for(int n=0; n<=i; n++)
    Even if this were to magically create an array of 200 elements, your for loop is still a buffer overrun.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by brassbin View Post
    i'm using gcc version 4.4.7, and compiling like this

    gcc -std=c99 test.c -o test
    Compile like this instead (warnings are your friend):

    Code:
    gcc -std=gnu99 -Wall -Wextra -o test test.c
    I use gnu99 with GCC because without it it sometimes gives me some weird problems. Just avoid using the GNU extensions if you want your code to be portable.

  4. #4
    Registered User
    Join Date
    Oct 2013
    Posts
    17
    Quote Originally Posted by Salem View Post
    >larger than your stack (99% of all positive numbers), you're screwed.
    Salem, would you mind elaborate on that? what is this "stack" you were referring to?

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    I think that Salem doesn't have to elaborate.
    Take this code
    Code:
    int main(void)
    {
         int a[5];
    
         ...
    
         return 0;
    }
    As one can see, the first line of main(), creates an array of type int, with a size equal to five.

    Now, consider this code.
    Code:
    int main(void)
    {
         int i, a[i];
    
         ...
    
         return 0;
    }
    As one can see, the first line of main(), declares a variable named "i", of type int and creates an array of type int, with a size equal to i.
    ..... Didn't I say enough?
    Print the value of i? Do you know what this value is from before? I think not! It is undefined behavior!
    "i" variable has a garbage value, since it is unintialized!
    So, you create an array of ints, with size equal to a garbage value.
    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

  6. #6
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I don't think that code is pedantic and should be avoided, std. Or at least, I'm pretty sure the ISO standard forbids static declarations that way.

    Edit : I just tried it with some C++ code and yeah, it claims the standard forbids the declaration of variable length arrays not known at compile time. malloc should be used instead.

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MutantJohn View Post
    Edit : I just tried it with some C++ code and yeah, it claims the standard forbids the declaration of variable length arrays not known at compile time. malloc should be used instead.
    C++ may forbid it. C does not.

  8. #8
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Really? That's fascinating. Do you know why there's a difference between C and C++ here? This is one of those things that seems like they should both agree here. Does C handle stack allocations differently?

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MutantJohn View Post
    Really? That's fascinating. Do you know why there's a difference between C and C++ here? This is one of those things that seems like they should both agree here. Does C handle stack allocations differently?
    Variable-length arrays were created (in C) in the 1999 version of the standard, while the C++ standard (well, the one before C++11) came out in 1995. They could have added it in C++11, and if you look through a draft standard you can see if it's in there (and for that matter I suppose I could too), but since they created std::array I suspect they didn't bother.

    EDIT TO ADD: And now that I think about it, what kind of C++ compiler is recommending malloc instead of new?

  10. #10
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    But std::array requires that the size be known at compile time as well so that seems like a moot point to me. I tried googling about it and the reasons seem to be that C++ itself is unsafe (more 'unsafe' than C) and that C++ has superior options than variable length arrays, namely std::vector.

    At least, I'm pretty sure std::array requires the size be known at compile time because I think I remember trying to declare a std::array with a variable size and it wasn't compiling so I had to use std::vector.

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Yes, a std::array requires a fixed size. My point was more that given they were introducing the new array, they probably weren't going to bother fiddling with the "regular" array. (I don't always have the greatest grasp on human nature, but I'm thinking lazy is pretty universal.)

    But yes, the STL containers are often a good fit for what you're actually doing, and if you do want exactly a dynamically-sized array there's always new.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by tabstop
    what kind of C++ compiler is recommending malloc instead of new?
    One that shares a code base with a C compiler

    Quote Originally Posted by MutantJohn
    C++ itself is unsafe (more 'unsafe' than C)
    o_O
    Never heard this argument before. They both seem equally unsafe to me, but then that's mainly because C++ is somewhat of a superset of C.

    Quote Originally Posted by MutantJohn
    C++ has superior options than variable length arrays, namely std::vector
    Well, "superior" depends on what you need. If you want to have the array size fixed at runtime, then std::vector won't do unless you also declare it const, in which case you cannot modify the elements. (Then again, you can always write a container that has the given constraints, with the implementation simplified thanks to std::vector.) As far as I know, VLAs in C could be implemented to use the stack (though it isn't guaranteed), whereas std::vector in C++ uses the free store by default.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Oct 2013
    Posts
    17
    the word "stack" has been mentioned multiple times in this thread, would really appreciate if someone could explain in detail? does this have anything to do with compile-time allocation vs. run-time allocation? from what i can gather googling, it seesm variable length array uses run-time allocation...?

  14. #14
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Lol sorry, manger. Sometimes we get caught up in our own discussions.

    You should check out this link : Call stack - Wikipedia, the free encyclopedia

    It's a lot of reading but hopefully this will help you understand what's going on.

  15. #15
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with variable length array
    By skiabox in forum C Programming
    Replies: 11
    Last Post: 11-06-2010, 04:15 PM
  2. variable length array
    By fatsrir in forum C Programming
    Replies: 18
    Last Post: 06-04-2010, 10:52 AM
  3. Passing Variable-Length Array to a Function
    By murjax in forum C Programming
    Replies: 4
    Last Post: 07-24-2009, 09:36 PM
  4. Variable length array
    By 671 in forum C Programming
    Replies: 2
    Last Post: 09-13-2006, 01:05 PM
  5. Variable length
    By 182 in forum C++ Programming
    Replies: 9
    Last Post: 02-14-2006, 08:56 PM