By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,264 Members | 1,237 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,264 IT Pros & Developers. It's quick & easy.

Is there possible funky division going on here?

P: n/a
Given something like
#include <stdio.h>
#include <string.h>

int main(void)
{
char name[] = "chad";
int number = 2;
int val;

size_t len = strlen(name);

val = len/number ;

return 0;
}

[cdalten@localhost ~]$ gcc -g -Wall -ansi -pedantic div.c -o div

What if name[] is something really really long. Long enough to fill up
size_t in len. Wouldn't this value get truncated since val is int? And
if it does possibly get truncated, how come my compiler doesn't say
anyting?

Chad

Jun 19 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Chad <cd*****@gmail.comwrote:
Given something like
#include <stdio.h>
#include <string.h>

int main(void)
{
char name[] = "chad";
int number = 2;
int val;

size_t len = strlen(name);

val = len/number ;

return 0;
}

[cdalten@localhost ~]$ gcc -g -Wall -ansi -pedantic div.c -o div

What if name[] is something really really long. Long enough to fill up
size_t in len. Wouldn't this value get truncated since val is int?
Possibly, depending on the sizes of size_t and int. If size_t is at
least as large as int, the division is done unsigned. If it's exactly as
large as int, the result of dividing (what is in effect) any unsigned
int value by two is guaranteed to fit in a signed int.
And if it does possibly get truncated, how come my compiler doesn't say
anyting?
Who knows the motivations of the Ganuck implementors? Perhaps they do
static analysis on your code, and decide that in this case, strlen(name)
is always 4. Perhaps you need to crank up the optimisation level;
perhaps down.

Richard
Jun 19 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.