Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you store an extremely large single value in a dynamically allocated block of memory?

Why can't I store a large integer in this allocated block of memory?

int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

like image 452
joe. Avatar asked Dec 13 '22 09:12

joe.


1 Answers

*dyn = 9999999999; does not instruct the computer to use all the memory that was allocated for dyn to store the value 9999999999.

In C, dyn has a type. The type is “pointer to int”. Then *dyn has type int, which has a specific, fixed number of bits. It does not have a type meaning “all the memory that was allocated for dyn”.

Since *dyn is an int, *dyn = 9999999999; tells the computer to put 9999999999 into an int. Since 9999999999 is too big for an int in your C implementation, an overflow occurs.

We can program computers and design programming languages to manage integers of arbitrary sizes. Some languages, such as Python, do this. However that requires extra software, particularly software that has to do some variable amount of work when the program is running in order to handle whatever sizes of numbers come along. C is designed to be an elementary language. It works with objects of specific sizes and generally translates C code to fixed amounts of work in processor instructions. These provide building blocks for programmers to build bigger software. So, in C, int objects have fixed sizes. Allocating 16 bytes of memory provides space for several int objects, but it does not provide a big integer object.

like image 98
Eric Postpischil Avatar answered Jan 17 '23 16:01

Eric Postpischil