venkysmarty
venkysmarty

Reputation: 11431

static_cast cannot convert from void* to size_t error in C++ in VS 2010

I am having following code which I am getting following error

error C2036: 'void *' : unknown size
error C2440: 'static_cast' : cannot convert from 'void *' to 'size_t'

at line

void *addr = static_cast <void*> (static_cast <size_t> (mem + bytesAlreadyAllocated));

My question is why I am getting above errors and how to get rid of these errors?

Thanks for help.

class MemoryChunk {
public:
    MemoryChunk (MemoryChunk *nextChunk, size_t chunkSize);
    ~MemoryChunk() {delete mem; }

    inline void *alloc (size_t size);
    inline void free (void* someElement);

    // Pointer to next memory chunk on the list.
    MemoryChunk *nextMemChunk() {return next;}
    // How much space do we have left on this memory chunk?
    size_t spaceAvailable() { return chunkSize - bytesAlreadyAllocated; }

    // this is the default size of a single memory chunk.
    enum { DEFAULT_CHUNK_SIZE = 4096 };
private:

    // The MemoryChunk class is a cleaner version of NextOnFreeList. It separates the next pointer from
    // the actual memory used for the allocated object. It uses explicit next and mem pointers, with no 
    // need for casting.

    MemoryChunk *next;
    void *mem;

    // The size of a single memory chunk.
    size_t chunkSize;
    // This many bytes already allocated on the current memory chunk.
    size_t bytesAlreadyAllocated;
};

MemoryChunk::MemoryChunk(MemoryChunk *nextChunk, size_t reqSize) {
    chunkSize = (reqSize > DEFAULT_CHUNK_SIZE) ? reqSize : DEFAULT_CHUNK_SIZE;
    next = nextChunk;
    bytesAlreadyAllocated = 0;
    mem = new char [chunkSize];
}

void* MemoryChunk :: alloc (size_t requestSize) {
    void *addr = static_cast <void*> (static_cast <size_t> (mem + bytesAlreadyAllocated));
    bytesAlreadyAllocated += requestSize;
    return addr;
}

inline void MemoryChunk :: free (void *doomed) {}

Upvotes: 3

Views: 2829

Answers (1)

justin
justin

Reputation: 104698

the expression:

static_cast <size_t> (mem + bytesAlreadyAllocated)

applies an offset using a type of undefined size (void). since void has no size, the program is ill formed.

char* is a suitable pointer for your usage in this scenario. for example:

`char* mem;`
 // and
 char* addr(mem + bytesAlreadyAllocated);

Update

So in the following program:

#include <iostream>

int main(int argc, const char* argv[]) {
    const int array[3] = {-1, 0, 1};
    std::cout << *(array + 0) << ", "
      << *(array + 1) << ", " << *(array + 2) << "\n";
    return 0;
}

The output is -1, 0, 1. The element offsets are applied based on the size and type of the array elements. With void -- size is not proper.

Upvotes: 4

Related Questions