由函数参数定义的数组

时间:2022-12-26 19:34:17

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?

为什么foo上面的数组定义很危险?

1 个解决方案

#1


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.

它是危险的,因为在C99及更高版本中,你可以分配可变长度数组(VLA),没有办法判断分配是否成功。如果失败,可能的结果是崩溃 - 或者更糟糕的是,无声的数据损坏。

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

与malloc不同,malloc在无法满足请求时返回NULL。

#1


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.

它是危险的,因为在C99及更高版本中,你可以分配可变长度数组(VLA),没有办法判断分配是否成功。如果失败,可能的结果是崩溃 - 或者更糟糕的是,无声的数据损坏。

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

与malloc不同,malloc在无法满足请求时返回NULL。