-1

in my OS long long int is : 8 bytes . int is 4 bytes .

int *p = malloc(4);

this code allocate 4 bytes for a variable of type integer on the heap .

int *p = malloc(8);

will this allocate a long long integer like 'one variable' or two items on an array .

how can i allocate an integer of 8 bytes long ? how can i allocate an array containing 2 items ?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    `malloc()` doesn't know anything about the type of data, it just allocates memory. – Barmar Oct 30 '20 at 21:54
  • `malloc()` does not care about data type sizes. It's up to you to do the math when allocating memory of size * your data type size. – Irelia Oct 30 '20 at 21:56
  • 1
    Related to: https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc (first comment to the question and accepted answer) – Jose Oct 30 '20 at 21:59

2 Answers2

1

malloc() just allocates raw memory, whether it's treated as an array or a single variable is determined by how the memory is used in the caller.

int *p = malloc(2 * sizeof(int));

treats the memory as an array of 2 int. You can then do:

p[0] = 1;
p[1] = 2;

and it will write two int into the memory.

long int *p = malloc(sizeof(long int));

treats the memory as a single long int (or, equivalently, an array of 1 long int). Then you can do:

*p = 12345678;

and it will write that long integer into the memory.

Both of them will allocate 8 bytes of memory on a system where int is 4 bytes and long int is 8 bytes.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you want an 8 byte integer, it's called a long long or int64_t/int64_t:

If this is about C, then you use malloc:

int64_t* p = malloc(sizeof(int64_t));

If this is about C++, then you use new:

int64_t* p = new int64_t;

With your original code you're getting an allocation of arbitrary size mapped to a pointer of a fixed size type, where int is typically 4 bytes, or in other words, you have room for int[2].

Note: For portability reasons it's always best to express your allocations in terms of base types, not just abstract numbers. malloc(8) may allocate memory for 2 x int, or it may not, that depends on what sizeof(int) is. malloc(sizeof(int) * 2) always works correctly.

tadman
  • 208,517
  • 23
  • 234
  • 262