Question

I'm trying to find the equivalent of int myArray[n], except I don't know what n is without input.

Is the following code supposed to work? (I need to use kmalloc instead of malloc).

int * pages;
//... later, after we find out n...
pages = (int *)kmalloc(npages * sizeof(int));

Debugging using gdb, the value pages[0] doesn't seem to be 0 - is this expected?

Was it helpful?

Solution

Yes. Memory is not initialized, you just get a pointer to your chunk of memory.

You'll need to memset to initialize it:

memset(pages, 0, npages * sizeof(int));

Also, unless I'm mistaken kmalloc takes a second parameter, the type of memory to allocate.

OTHER TIPS

malloc returns a pointer to some location on the heap that it has allocated for your array. It does not initialize that memory. You can use calloc instead of malloc to have the memory be initialized (set to zero), or you can use memset after you allocate the memory and set the memory to zero yourself.

Since you are using kmalloc, you'll probably have to use memset; I don't believe there is a cmalloc for allocating initialized memory in the kernel.

Alternatively you could use the kernel function kzalloc:

int * pages;
pages = (int *)kzalloc(npages * sizeof(int), GFP_KERNEL);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top