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;