0

I've never done this, but I'm not sure why the below array definition is wrong.

I have this example code:

typedef struct _SomeObjType {
   int val;
   ...
} SomeObjType;

static SomeObjType *oObject = NULL;
oObject = malloc( sizeof(SomeObjType) );
oObject->val = 300;

static Err foo (SomeObjType *object) {
   if(object == NULL) 
   return -1;

   unsigned char table[object->val];
   ...
}

Why is the above array definition in foo dangerous?

avis21
  • 1
  • 2
  • It's not _dangerous_ but you need some extra-care (to do not exhaust stack), it's also _wrong_ in C90 but it's allowed in C99 (if array size is unknown at compile-time then you have to use _dynamic arrays_ allocated with malloc). – Adriano Repetti Oct 07 '15 at 08:28
  • See [Is it safe to use variable-length arrays?](http://stackoverflow.com/questions/7326547/is-it-safe-to-use-variable-length-arrays) – David Ranieri Oct 07 '15 at 08:29

1 Answers1

2

It's dangerous in that in C99 and beyond, where you can allocate variable length arrays (VLA), there is no way to tell whether the allocation succeeded. If it failed, the likely outcome is a crash--or worse, silent data corruption.

Unlike malloc, which returns NULL when it can't satisfy the request.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • 1
    It is just as dangerous as calling a function. You have no way to tell whether there's enough memory for another stack frame. – n. m. could be an AI Oct 07 '15 at 08:46
  • Thank you for explanation and about VLA. Now I know new phrase and I still will not use VLA, but malloc as usually. – avis21 Oct 07 '15 at 09:28
  • @n.m. While this is true for the general case, there is a large class of programs, those without recursive calls, where the maximum stack use is fixed and can be determined through static analysis. This is commonly done for embedded systems, where a stack size must be specified on a per thread/process basis. This static analysis is impossible when VLA are used. – Jens Oct 07 '15 at 09:34