Visual C++ Warning C4305: Initializing truncation from int to unsigned char

Chaotic42

Lifer
Jun 15, 2001
33,929
1,098
126
I'm off on another C++ programming adventure and this time I'm dealing with creating an array of unsigned chars of a certain size. The program works fine, but VC++ gives me a warning when I request more than 255 of these:

Code:
// I get a warning from this
unsigned char* out = new unsigned char(256);

// I get no warning from this
unsigned char* out = new unsigned char(255);

Specifically the warnings I get are:

Code:
Warning C4305: 'initializing': truncation from 'int' to 'unsigned char'
Warning C4309: 'initializing': truncation of constant value

Now I get that 255 is the largest value which can be stored in an unsigned char, but my understanding is that this code is requesting a 32-bit memory address pointing to the first of 256 unsigned chars and storing that value into a 32-bit-large pointer to unsigned chars.

What am I missing here?
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
So what you're doing is dynamically allocating a single unsigned char, and initializing it with a value. That's ok for an initial value of 255, because as you note it fits. But 256 does not. What you really want is:

unsigned char* out = new unsigned char[256];
 

Schmide

Diamond Member
Mar 7, 2002
5,587
719
126
When you use () on a primitive like char it assigns the that value to the created primitive. So you are only creating 1 primitive with a value of 256 which overflows a char. Thus the warning.

I think you're looking to do a

Code:
unsigned char* out = new unsigned char[255];
 

Net

Golden Member
Aug 30, 2003
1,592
2
81
since everyone else already answered the main part, I'll comment on the last part.

Now I get that 255 is the largest value which can be stored in an unsigned char, but my understanding is that this code is requesting a 32-bit memory address pointing to the first of 256 unsigned chars and storing that value into a 32-bit-large pointer to unsigned chars.

Your pointer size will be different based on the architecture of the system. Generally, 2 bytes for 16-bit, 4 bytes for 32-bit, 8 bytes for 64-bit (this doesn't include function pointers, those are different). I say generally because there are cases where this isn't true (i.e. 16-bit DOS/Windows, different platforms)

Code:
size_t s = sizeof(unsigned char*);

nice graphic here: http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.html
 
Last edited: