473,785 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Integer overflow in expression

Hi,
I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,

In function `main':
:4: warning: integer overflow in expression

but when I use this

int main() {
unsigned long x = 0xC0000000; /* 3GB */
printf(" %x ", x);
}

It doesn't give out any errors. Any idea as to why its warning about
integer overflow when it is well within the range of 32bits ? My gcc
-v

Configured with: FreeBSD/i386 system compiler
Thread model: posix
gcc version 3.3.3 [FreeBSD] 20031106

Vivek
Nov 14 '05 #1
7 17808

"Vivek Mohan" <vi****@phreake r.net> wrote in message

unsigned long x = 3*1024*1024*102 4; /* 3GB error*/
unsigned long x = 0xC0000000; /* 3GB OK*/

The compiler treats raw decimal integers as signed ints by default.If you
tag an "lu" on the end it will be OK.
Nov 14 '05 #2
Vivek Mohan wrote:

I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,

In function `main':
:4: warning: integer overflow in expression
The compiler considers the constants 3 and 1024 to be of type int. So
the result of the multiplication expression (3*1024*1024*10 24) is also
int. But the result is too large to be represented as an int, so the
compiler complains of integer overflow.

You need to arrange things so that the result of the expression is an
unsigned long. Simply assigning the result to an unsigned long variable
won't do it. You should force the compiler to treat each operand in the
expression as an unsigned long, like this:

unsigned long x = 3ul * 1024ul * 1024ul * 1024ul;

Two other things: you forget to #include <stdio.h> (for printf), and the
conversion specifier in the printf statement should be %lx, not %x,
because x is an unsigned long.
but when I use this

int main() {
unsigned long x = 0xC0000000; /* 3GB */
printf(" %x ", x);
}

It doesn't give out any errors.


The compiler sees that the constant 0xC0000000 can't be represented as
an int, so it regards it as some other type--maybe unsigned long.

--
Russell Hanneken
rg********@pobo x.com
Remove the 'g' from my address to send me mail.
Nov 14 '05 #3
Vivek Mohan wrote:
Hi,
I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,

In function `main':
:4: warning: integer overflow in expression


"3" and "1024" are both integers so you're calculating using integer
math. Specify one/both as a long constant.
Nov 14 '05 #4
In article <41************ **************@ posting.google. com>, Vivek Mohan wrote:
Hi,
I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,

In function `main':
:4: warning: integer overflow in expression [-]
3 (signed) * 1024 (signed) * 1024 (signed) * 1024 (signed)
[-] but when I use this

int main() {
unsigned long x = 0xC0000000; /* 3GB */
printf(" %x ", x);
} [-]
Or this ...
3 * 1024 * 1024 * 1024u
.... or this ...
3u * 1024 * 1024 * 1024
.... or ...
It doesn't give out any errors.

[-]

Cheers,
Juergen

--
\ Real name : Juergen Heinzl \ no flames /
\ Email private : ju*****@mananna n.org \ send money instead /
\ Photo gallery : www.manannan.org \ /
Nov 14 '05 #5
Vivek Mohan wrote:

Hi,
I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,

In function `main':
:4: warning: integer overflow in expression


`3' is a signed int, and so are all three appearances
of `1024'. You have asked for these four signed ints to
be multiplied together, producing a product that is also
a signed int, and then for that signed int product to be
converted to unsigned long. The compiler is telling you
that the product is too large to fit in a signed int.

Here's a fix:

unsigned long x = 3u * 1024u * 1024u * 1024u;

Now all the operands are unsigned ints, and the product
is also an unsigned int. The product will not overflow a
32-bit unsigned int, so all will be well.

... maybe. It appears that your compiler uses 32 bits
for an int, but not all compilers do so. The C language
guarantees that an int has at least 16 bits, but does not
require it to be wider. If int (and hence unsigned int)
are 16 bits wide (or 18, or 24, or anything less than 32),
the product will not be "3GB" as you expect.

Here's a better fix:

unsigned long x = 3ul * 1024ul * 1024ul * 1024ul;

This time, all the operands are unsigned longs. In all C
implementations , long and unsigned long are at least 32
bits wide, possibly wider. That means that your calculation
will now behave as you intended, regardless of the platform.

By the way, you should use "%lx" rather than just "%x"
to print the value; the 'l' tells printf() that the operand
is "long" instead of "plain." You mention that you're using
gcc; if you run it as "gcc -Wall -W" it will catch this error
for you. (In my own work, I also add "-ansi -pedantic" for
all modules that can tolerate it; some system-dependent
modules cannot.)

--
Er*********@sun .com
Nov 14 '05 #6
Vivek Mohan wrote:
Hi,
I am using gcc, and I am a bit confused about the warning message I
got when I compiled and ran this small code snippet -

int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}

I got the following error,
You should get more.
In function `main':
:4: warning: integer overflow in expression


The expression on the right of the equal sign has no longs (not to
mention unsigned longs), so is computed as an int. Try this fixed
version of your code:

#include <stdio.h> /* mha: fixed omitted header, providing
prototype required for variatic
function printf */
int main()
{
unsigned long x = 3ul * 1024 * 1024 * 1024; /* mha: fixed
initializer */
printf(" %lx\n", x); /* mha: fixed wrong specifier; fixed
implementation-specic behavior for
last output line not terminated with
an end-of-line character */
return 0; /* mha: added for the almost 100% of
people with C89, not C99 compilers */
}

Nov 14 '05 #7
Russell Hanneken <rg********@pob ox.com> wrote:
Vivek Mohan wrote:
int main() {
unsigned long x = 3*1024*1024*102 4; /* 3GB */
printf(" %x ", x);
}
You need to arrange things so that the result of the expression is an
unsigned long. Simply assigning the result to an unsigned long variable
won't do it.
The reason for this, BTW, is that by the time the assignment is done,
the computation has already been performed using ints.
You should force the compiler to treat each operand in the
expression as an unsigned long, like this:

unsigned long x = 3ul * 1024ul * 1024ul * 1024ul;


No need. All you need is to force it to consider the first operand to be
an unsigned long; automatic promotions will ensure that the rest will be
promoted before being multiplied.

Richard
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
2378
by: Russell Shaw | last post by:
Hi, I'm using gcc-3.4.3 on a linux pc. The ints and long ints are 32 bits and long long ints are 64 bits. When i have: int num=9600; long long int reg=(long long)800000000000/(5000000*num); the denominator overflows and gives an incorrect answer: reg=1059
25
521
by: bruce.james.lee | last post by:
hi i have a problem with integer subtraction in C. printf("%d", c < (a - b)); a is got from a #define and is 0x80000000 and b is got from input and is also 0x80000000. c is ffffffff (-1). Now, this should print 1 (true) but it prints 0! If I modify this to d = c < (a - b);
25
6275
by: junky_fellow | last post by:
Is there any way by which the overflow during addition of two integers may be detected ? eg. suppose we have three unsigned integers, a ,b, c. we are doing a check like if ((a +b) > c) do something;
33
2343
by: dragoncoder | last post by:
Hi all, Does the following code invoke undefined behaviour ? $ cat a1.cc #include <iostream> #include <limits> int main() { int a = INT_MAX/2;
40
2815
by: Robert Seacord | last post by:
The CERT/CC has released a beta version of a secure integer library for the C Programming Language. The library is available for download from the CERT/CC Secure Coding Initiative web page at: http://www.cert.org/secure-coding/ The purpose of this library is to provide a collection of utility functions that can assist software developers in writing C programs that are free from common integer problems such as integer overflow, integer...
13
3227
by: Freaker85 | last post by:
Hello, I am new at programming in C and I am searching a manner to parse a string into an integer. I know how to do it in Java, but that doesn't work in C ;o) I searched the internet but I didn't found it yet. help please thank you Freaker85
1
3787
by: charles_gero | last post by:
Hi all, I had a question about the topics in the subject and posted to comp.std.c, but feel it may also be appropriate here. Please excuse this crosspost if it is in bad form. I have a question about whether or not I am interpreting a nuance of the standard correctly, and the implications of said nuance. The sections in the C99 standard (and possibly older standards) that I will reference are as follows (typed out hopefully to avoid...
232
13349
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
42
7036
by: thomas.mertes | last post by:
Is it possible to use some C or compiler extension to catch integer overflow? The situation is as follows: I use C as target language for compiled Seed7 programs. For integer computions the C type 'long' is used. That way native C speed can be reached. Now I want to experiment with raising a Seed7 exception (which is emulated with setjmp(), longjmp() in C) for integer
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.