Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler warning "result of malloc is converted to a point incompatible with sizeof operand type"

I have these defined in the interface of an ObjC class:

unsigned m_howMany;
unsigned char * m_howManyEach;
...

Then later in the code I have this:

 m_howManyEach = malloc(sizeof(unsigned) * m_howMany);

which is where I get a warning "Result of malloc is converted to a pointer of type unsigned char, which is incompatible with sizeof operand type unsigned int"

Could someone please explain the proper use of malloc() in this situation, and how to go about getting rid of the warning?

like image 964
EarlGrey Avatar asked Dec 27 '22 18:12

EarlGrey


1 Answers

First, unsigned is really unsigned int.

The compiler is being nice to you, telling you that you are allocating N items of unsigned, which is not unsigned char.

Also, your later access will be wrong as well.

Change

unsigned char * m_howManyEach;

to

unsigned * m_howManyEach;

because it looks like you really want unsigned int as your type instead of unsigtned char.

Of course, this assumes you really want unsigned integers, and not 1-byte unsigned chars.

If the actual size of your integral values is important, you should consider the sized valued (uint8_t, uint16_t, uint32_t, uint64_t).

like image 119
Jody Hagins Avatar answered Mar 22 '23 22:03

Jody Hagins