ktan
ktan

Reputation: 13

GCC warning with c type casting

I was trying to compile an old project on a new system, but I got a "cast from pointer to integer of different size" warning with the new system.

Here's the source code:

void mem_fill(char *myptr, char *mystr, uint32_t sz)
{           
    uint32_t len = strlen((const char*)mystr);
    if (len > sz) len = sz;
    memset(myptr, (int)NULL, sz); // <-- Warnning reported here
    memcpy(myptr, mystr, len);
}

NULL is defined like:

#define NULL    (void *)0

The old system won't report this error, it's RHEL4, gcc version 3.4.4 20050721. New system is Cent OS 6.5, gcc version 4.4.7 20120313

I tried to replace casting type "int" with "long", then the new system won't report this error again, it looks like new system has 64 bit pointer. However, if I replace "int" with long/char/short, all types can pass build on the old system.

Here's my question, why does new system report this casting warning but old system doesn't? The source code is the same, so is there any other default settings for gcc hidden somewhere in the developing environment?

It's a good point of view that this function is equivalent to strncpy. Actually my problem is - why doesn't my old system report this casting warning but new system does, is it caused by different version of GCC?

Thanks all guys for your help.

Upvotes: 1

Views: 840

Answers (2)

Yu Hao
Yu Hao

Reputation: 122373

Use 0 directly instead of (int)NULL.

memset(myptr, 0, sz);

There's no warning in the old system is probably because NULL is defined as:

#define NULL 0

Both definitions of NULL is legal in standard C.

Upvotes: 2

M.M
M.M

Reputation: 141544

Change (int)NULL to 0. The argument is supposed to be a byte value to fill the memory in with, whoever wrote that code the first time didn't understand the difference between a null pointer and a byte of value zero.

Upvotes: 4

Related Questions