Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Sort of OT, but I've been writing some malloc-less C lately, where most/all memory is on the stack, and I've been wishing for a way to control the space with a function argument, for example:

    void foo(int x) {
      char c[x]; 
      // . . .
    }
I'm pretty sure there is no way to do that in C, but I'm wondering if a bit of (Intel) assembly could give me something re-useable from a C context. Any ideas?


Doesn't `alloca` do exactly what you want? http://man7.org/linux/man-pages/man3/alloca.3.html


Yes and now C99 supports variable length arrays anyway. The storage gets allocated (deallocated) as control enters (exits) the scope. Jumping in I think is not allowed, dunno if that gets compile time checked or results in a run time error. alloca is officially not portable but its present on platforms I care about. It is living dangerously, sure, but quite effective nonetheless.

Would have loved a portable way to query how much stack space the process has left. The problem some architectures need not even have a stack.

@dbaupp Hey thanks ! and nice to know


It's a compile time error, e.g.

  void foo(int x) {
    goto label;
    {
        char y[x];
  label:
        y[0] = 'a';
    }
  }

  alloca-goto.c: In function ‘foo’:
  alloca-goto.c:2:5: error: jump into scope of identifier with variably modified type
       goto label;
       ^
  alloca-goto.c:5:1: note: label ‘label’ defined here
   label:
   ^
  alloca-goto.c:4:14: note: ‘y’ declared here
           char y[x];
                ^




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: