Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid using variable-length array #14

Merged
merged 1 commit into from
Jun 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions fibdrv.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/version.h>

MODULE_LICENSE("Dual MIT/GPL");
Expand All @@ -25,10 +26,18 @@ static struct class *fib_class;
static DEFINE_MUTEX(fib_mutex);
static int major = 0, minor = 0;

/**
* fib_sequence() - Calculate the k-th Fibonacci number
* @k: Index of the Fibonacci number to calculate
*
* Return: The k-th Fibonacci number on success, -ENOMEM on memory allocation
* failure.
*/
static long long fib_sequence(long long k)
{
/* FIXME: C99 variable-length array (VLA) is not allowed in Linux kernel. */
long long f[k + 2];
long long *f = kmalloc(sizeof(*f) * (k + 2), GFP_KERNEL);
if (!f)
return -ENOMEM;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provide explicit comments for this function.


f[0] = 0;
f[1] = 1;
Expand All @@ -37,7 +46,11 @@ static long long fib_sequence(long long k)
f[i] = f[i - 1] + f[i - 2];
}

return f[k];
long long ret = f[k];

kfree(f);

return ret;
}

static int fib_open(struct inode *inode, struct file *file)
Expand Down
Loading