Domanda

I need to allocate all the memory my application will use up front. And then whenever needed overwrite that memory with data I need to do computations on. The memory has to be allocated first before any computations because I'm trying to run a multi-threaded CUDA algorithm in parallel as explained in my question here (Multi-Threaded CPU CUDA application not asynchronous when calling CudaFree).

I thought I could allocate all the memory needed as a byte pointer and then store that pointer as a void pointer:

void * allocateMemory()
{
    byte *mem;
    int nbytes = 13107200;
    mem = (byte *) malloc(nbytes);
    return mem;
}

Later in my program I want to use the memory that's already allocated to store data. I don't know ahead of time what type the data will be but I know it's size won't go over the allocated limit.

void doSomething(void * mem)
{
    int *a = (int*) mem;
    for (int i = 0; i < 100; i++)
    {
        a[i] = i;
    }

    //do stuff

}

There are many other functions like doSomething(void * mem) above but that use type double or type float or maybe even type byte. I need to be able to overwrite the orignally allocated memory with whatever data type I need. The above code does not work because it says I can't deference a void pointer. It also says I attempted to read or write protected memory.

What is the proper way to do this? What is the best way to accomplish my goal of having all my memory allocated at the beginning and then used however necessary throughout? Thanks!

È stato utile?

Soluzione

It sounds like you have two problems.

  1. Cannot dereference a void pointer. Somewhere in your code you have used the result from allocateMemory() without a cast. The code you give is OK, but whatever line the compiler is flagging as wrong is not OK. For example, maybe you have:

    void *foo = allocateMemory();
    foo[42];  // compiler doesn't have a real type here - error
    ((int*)foo)[42];  // compiler happy
    
  2. Attempted to access protected memory. Somewhere in your code you have an invalid pointer. The most likely cause is that allocateMemory() is returning NULL (which you are not checking for).

Your general approach seems OK to me; the issues you describe are related to details in your code, not the overall idea.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top