Skip to content

Commit c318f72

Browse files
committedJun 12, 2024
Avoid using variable-length array
Using variable-length array is not a good call (https://lkml.org/lkml/2011/10/23/25). So remove it. Signed-off-by: Eric Lin <ericlinsechs@gmail.com>
1 parent 5ce76d4 commit c318f72

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed
 

‎client.c

+8
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ int main()
2929
for (int i = 0; i <= offset; i++) {
3030
lseek(fd, i, SEEK_SET);
3131
sz = read(fd, buf, 1);
32+
if (sz < 0) {
33+
perror("Failed to read character device");
34+
exit(1);
35+
}
3236
printf("Reading from " FIB_DEV
3337
" at offset %d, returned the sequence "
3438
"%lld.\n",
@@ -38,6 +42,10 @@ int main()
3842
for (int i = offset; i >= 0; i--) {
3943
lseek(fd, i, SEEK_SET);
4044
sz = read(fd, buf, 1);
45+
if (sz < 0) {
46+
perror("Failed to read character device");
47+
exit(1);
48+
}
4149
printf("Reading from " FIB_DEV
4250
" at offset %d, returned the sequence "
4351
"%lld.\n",

‎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 -1;
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)