Unix Technical Forum

Re: more improvements for mg

This is a discussion on Re: more improvements for mg within the mailing.openbsd.tech forums, part of the OpenBSD category; --> On Mon, May 16, 2005 at 09:59:04AM -0600, Todd C. Miller wrote: > In message <20050516151748.GA1337@moule.localdomain> > so spake ...


Go Back   Unix Technical Forum > Unix Operating Systems > OpenBSD > mailing.openbsd.tech

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 02-18-2008, 07:50 AM
Zvezdan Petkovic
 
Posts: n/a
Default Re: more improvements for mg

On Mon, May 16, 2005 at 09:59:04AM -0600, Todd C. Miller wrote:
> In message <20050516151748.GA1337@moule.localdomain>
> so spake Alexandre Ratchov (alex-contact):
>
> > int ret;
> > char foo[100];
> >
> > ...
> > ret = snprintf(foo, sizeof(foo), "%s", input);
> > if (ret < 0 || (size_t)ret >= sizeof(foo))
> >
> >
> > -1 means that snprintf failed and negative number of chars is meaningless.
> > This works if sizeof(foo) > INT_MAX because res is converted to size_t.
> > Have i missed something?

>
> While this does look OK I really don't see the need for the cast
> to size_t. In practice sizeof(foo) will not be > INT_MAX unless
> you are creating 2GB data structures on the stack and the stack is
> not big enough to hold such a data structure anyway.


I agree that cast is not necessary since even lint doesn't complain
about it. It doesn't hurt to have the cast either, since that cast
_will_ happen implicitly anyway. In the above program it doesn't matter
since a positive number has a 0 for the most significant bit and remains
the same when cast to unsigned.

If sizeof returns size_t, and size_t is typedefed as unsigned int,
according to the implicit expression casting rules,
int _will_ be cast into unsigned when compared to an unsigned number.

For example this program

#include <stdio.h>
#include <limits.h>

int
main(int argc, char *argv[])
{
int x = INT_MIN;
size_t y = INT_MAX;

printf("INT_MIN = %d\nINT_MAX = %d\n", INT_MIN, INT_MAX);
if (x > y)
printf("\nCast: INT_MIN > INT_MAX unsigned\n");

return 0;
}

produces

$ make tryme
cc -O2 -o tryme tryme.c
$ ./tryme
INT_MIN = -2147483648
INT_MAX = 2147483647

Cast: INT_MIN > INT_MAX unsigned

Thus, with or without explicit cast to size_t, the cast will happen.

Regards,

Zvezdan Petkovic

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 01:38 AM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0
www.UnixAdminTalk.com