0

I am learning about integer overflows and underflows and was wondering if it is it possible to control the value of j by giving a negative input n?

int i = n;
size_t j = i;
printf("%lu",j);

for example, if I want the value of "j" to be 255, is it possible to craft the negative number "n" to give me that output?

12
  • 3
    Yes it is! You can set n to 255. :-P Commented Sep 20, 2017 at 3:29
  • There's no such thing is "integer underflow", In the generally accepted nomenclature, "underflow" can only happen in floating-point arithmetic. As your your question, the answer is simple: just set your n to 255. The simplicity and triviality of the answer makes one suspect that you missed something in your question. Commented Sep 20, 2017 at 3:30
  • 1
    i'm sorry, i meant by giving negative value. i have updated the question Commented Sep 20, 2017 at 3:31
  • What is the type of n? Anyway, it is not possible to answer the question about negative value of n without knowing the exact characteristics of size_t type (its range, specifically). It is platform-dependent. And you should use %zu to print size_t values, not %lu. Commented Sep 20, 2017 at 3:32
  • 1
    If you cast a variable containing -1 to an uint8_t, you'll get 255. However, 255 is less than 0x8000, so I don't think you'll be able to get it by casting a negative to any integer type larger than 8 bits. And needless to say, I don't think you're going to find any modern platforms (or ancient ones, for that matter) on which unsigned long is only 8 bits in size. Commented Sep 20, 2017 at 3:36

1 Answer 1

1

I think what you're looking for is

signed char i = -1;
unsigned char j = i;
printf("%u\n", j);

In 8 bits, the signed number -1 "wraps around" to the unsigned value 255.

You asked about size_t because, yes, it's an unsigned type, but it's typically 32 or even 64 bits. At those sizes, the number 255 is representable (and has the same representation) in both the signed and unsigned variants, so there isn't a negative number that corresponds to 255. But you can certainly see similar effects, using different values. For example, on a machine with 32-bit ints, this code:

unsigned int i = 4294967041;
int j = i;
printf("%d\n", j);

is likely to print -255. This value comes about because 2^32 - 255 = 4294967041.

Sign up to request clarification or add additional context in comments.

1 Comment

In the latter code, the behaviour is implementation-defined (and may raise a signal)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.