Search code examples
c++bufferdynamic-memory-allocation

Assigning Values to unsigned short* buffer


I am having issues assigning value to unsigned short* and unsigned char* buffers. The code looks something like this:

// Header File
unsigned short* short_buff;
unsigned char* char_buff;
// Implementation File
short_buff = new unsigned short[10];
memset(&short_buff, 0, 10);

char_buff = new unsigned char[10];
memset(&char_buff, 0, 10);

unsigned short sVal = 0;
unsigned char cVal = 0x0;

// All of these cause core dumps
short_buff[0] = sVal;
memcpy(&short_buff[0], &sVal, 2); // 2 bytes per unsigned short
std::cout << short_buff[0] << std::endl;

// All of these also cause core dumps
char_buff[0] = cVal;
memcpy(&char_buff[0], &cVal, 1); // 1 byte per unsigned char
std::cout << char_buff[0] << std::endl;


// Yet strangely these cause no issues
unsigned short s2Val = short_buff[0];
unsigned char c2Val = char_buff[0];

I am completely at a loss as to what is going on here and why.. Any help would be greatly appreciated!


Solution

  • memset(short_buff, 0, 10*sizeof(short));
    

    and

    memset(char_buff, 0, 10*sizeof(char));
    

    Two mistakes, & is wrong, you should pass the value of the pointer to memset not the address of the pointer variable. (This version memset(&short_buffer[0], ...); also works).

    Secondly memset counts bytes not elements, so you need to multiply the array size by the element size, use sizeof for that.

    Strangely you got it more or less right with memcpy later on. Why not the same thing for memset?