Question

Whats wrong with this usage

void* buffer ; 
buffer = (void *)malloc(4096) ; 
memset( buffer, 0, sizeof(buffer) ); 

int *data = static_cast<int*>(buffer) ;
for(int i=0 ; i<10 ; i++)
{
    cout<< data[i] << "\n" ;
}

I get garbage values in the output. Am I using memset wrong ?

Was it helpful?

Solution

sizeof(buffer) is returning you the size of void* (the size of a void pointer). Which has nothing to do with the size of memory block.

The size of void* is commonly 4 or 8 bytes, but this depends on the platform. So memset() is only clearing a few bytes in the beginning of the array. To clear all of it, you have to pass in the exact size in bytes of the array. In this case 4096.

sizeof would actually return the size in bytes of the memory block if it where a block statically allocated, such as char buffer[4096]. Remember that sizeof is resolved at compile-time. So the static array is the only case when the compiler can resolve the length of an array. With a dynamically allocated array, the compiler has no way of knowing the size. Regardless of the array data type, char*, int*, std::string*, calling sizeof on the pointer will always return the size of the pointer variable, not the size of the memory it points to.

OTHER TIPS

As glampert already answered, the problem was that sizeof(buffer) doesn't express the amount of memory allocated, but the size of the pointer. So you could instead write

const int size = 4096;
void* buffer = malloc(size); 
memset( buffer, 0, size ); 

int *data = static_cast<int*>(buffer) ;
for(int i=0 ; i<10 ; i++)
{
    cout<< data[i] << "\n" ;
}
free( buffer );

Another way, perhaps a bit faster, would be

const int size = 4096;
void* buffer = calloc(size);  // return a newly allocated memory block which is zeroed

int *data = static_cast<int*>(buffer) ;
for(int i=0 ; i<10 ; i++)
{
    cout<< data[i] << "\n" ;
}
free( buffer );

But since you are using C++, it might be more appropriate to do it like this:

int *data = new int[ 10 ];
for ( int i=0; i < 10; i++ ) {
    data[ i ] = 0;
}
for( int i=0; i < 10; i++ ) {
    cout<< data[i] << "\n" ;
}
delete [] data;

Or even better:

int *data = new int[ 10 ](); // allocated array will be zeroed out
for( int i=0; i < 10; i++ ) {
    cout<< data[i] << "\n" ;
}
delete [] data;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top