Skip to content

Commit 61df593

Browse files
committed
Avoid using variable-length array
The size is always valid, but variable-length arrays generate worse code for no good reason, unless the function happens to be inlined and the compiler sees the length for the simple constant it is. Signed-off-by: Eric Lin <[email protected]>
1 parent 5ce76d4 commit 61df593

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

fibdrv.c

+9-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <linux/kernel.h>
77
#include <linux/module.h>
88
#include <linux/mutex.h>
9+
#include <linux/slab.h>
910
#include <linux/version.h>
1011

1112
MODULE_LICENSE("Dual MIT/GPL");
@@ -27,8 +28,9 @@ static int major = 0, minor = 0;
2728

2829
static long long fib_sequence(long long k)
2930
{
30-
/* FIXME: C99 variable-length array (VLA) is not allowed in Linux kernel. */
31-
long long f[k + 2];
31+
long long *f = kmalloc(sizeof(*f) * (k + 2), GFP_KERNEL);
32+
if (!f)
33+
return -ENOMEM;
3234

3335
f[0] = 0;
3436
f[1] = 1;
@@ -37,7 +39,11 @@ static long long fib_sequence(long long k)
3739
f[i] = f[i - 1] + f[i - 2];
3840
}
3941

40-
return f[k];
42+
long long ret = f[k];
43+
44+
kfree(f);
45+
46+
return ret;
4147
}
4248

4349
static int fib_open(struct inode *inode, struct file *file)

0 commit comments

Comments
 (0)