Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement malloc operation in C#

float **ThreadID;
int Nthreads;

How to perform below task in C#?

ThreadID = (float **)malloc( Nthreads* sizeof(float *) );
like image 809
user1561275 Avatar asked Jul 29 '12 17:07

user1561275


People also ask

How do you implement malloc?

malloc go through each block, from start to end, until one freed block has enought space. If no block was available, append the block to the end of the last heap . If the last heap has not enought available space, the algorithm creates a new heap by calling mmap.

How malloc is implemented internally?

When one calls malloc , memory is taken from the large heap cell, which is returned by malloc . The rest is formed into a new heap cell that consists of all the rest of the memory. When one frees memory, the heap cell is added to the end of the heap's free list.

How malloc and free is implemented in C?

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

How does malloc function work in C?

malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored. malloc() is part of stdlib. h and to be able to use it you need to use #include <stdlib.


2 Answers

Is there any reason why you need unmanaged memory for your application? Otherwise the normal way to do it would be

ThreadID = new float*[Nthreads];

That will allocate a new Array for you. If you use this kind of statement in a function that is called a lot, you might want to add the stackalloc-keyword. otherwise slow garbage collection could leed to increased memory consumption. With stackalloc it will be stored on the stack and destroyed as any other local variable upon leaving the function.

ThreadID = stackalloc float*[Nthreads];

EDIT: As with all pointers in C#, you need to declare the unsafe context for your function, like

unsafe int doSomething(){
   ...
}
like image 107
Legionair Avatar answered Sep 19 '22 20:09

Legionair


You can try using the following:

Marshal.AllocHGlobal 

Details are on MSDN here.

like image 21
Aghilas Yakoub Avatar answered Sep 21 '22 20:09

Aghilas Yakoub