views:

186

answers:

2

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?

+5  A: 

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.

James McNellis
Thanks for the answer!
stringo0
+2  A: 

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.

GMan
Thanks for the added example!
stringo0