DMaxter
DMaxter

Reputation: 178

C - int and malloc

Okay, I'm pretty new to those things. From what I've learned:

an int (signed int) is in range [−32,767; 32,767]
and a long long int (signed) is in range [-9,223,372,036,854,775,807; 9,223,372,036,854,775,807].

I also learnt that with malloc() function I can temporarily allocate memory for a variable.

I was thinking: if I use malloc() to allocate memory for a long long int, but with a larger size, can I store values bigger than 9,223,372,036,854,775,807 and smaller than -9,223,372,036,854,775,807?

Upvotes: 1

Views: 2958

Answers (2)

Peter
Peter

Reputation: 36617

an int (signed int) is in range [−32,767; 32,767] and a long long int (signed) is in range [-9,223,372,036,854,775,807; 9,223,372,036,854,775,807].

Partially true. Those are the minimum ranges that the standard requires an int and long long int to be able to represent.

The ranges are formally "implementation defined" i.e. fixed by the implementation (compiler, host system, standard library, etc), although they may vary between implementations. An implementation is permitted, but not required, to support a larger range of values for both types.

I also learnt that with malloc() function I can temporarily allocate memory for a variable.

Also approximately true.

malloc() can be used to dynamically allocate memory, which will remain allocated until a corresponding call of free() or on program termination (assuming a modern operating system that releases memory resources on program termination).

I was thinking: if I use malloc() to allocate memory for a long long int, but with a larger size, can I store values bigger than 9,223,372,036,854,775,807 and smaller than -9,223,372,036,854,775,807

This is an incorrect conclusion.

The size of all types (except char types, which are defined to have a size of 1) is also implementation-defined.

Yes, it is possible to allocate more memory using malloc(). But something like

int *p = malloc(2*sizeof(int));    /* assume the allocation succeeds */

does not create a bigger int, and does not affect the range of values an int can represent. It dynamically creates an array of TWO integers, which can be accessed as p[0] and p[1] (or, equivalently, *p and *(p+1)) respectively.

Upvotes: 3

Jacobm001
Jacobm001

Reputation: 4539

Sort of. The problem you're going to run into is that you don't have a type that fits the space. That means that your programming language doesn't have instructions on how to operate on numbers that large. Which means that you'll have to teach the language how to handle such a number, and you'll have to handle the fact that your CPU won't be able to handle the object natively.

To do so would require a lot of work on your part. This is a very simplified concept of what BigNum library is.

Upvotes: 2

Related Questions