Is there possible funky division going on here?

C

Chad

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
 
R

Richard Bos

Chad said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top