malloc function

I come across this code in an assignment. It is a MC question so it may be incorrect. I want to understand it first.
Does the 1st statement mean allocate 3 bytes to a long?
Does 'p += 3' mean incrementing the long *p for 3? Will it have memory of 3 times (size of long)?

Could anyone please explain? Thank you.

1
2
3
long *p = (long *)malloc(3);
p += 3;
free(p);
Last edited on
malloc() requests a block of memory from the heap, and free() returns it.

It's an error to free() a block of memory that wasn't obtained from malloc() (there are alternatives to malloc() than can be used; like calloc() and realloc()),

Your code gets some memory, increments the pointer by 3 bytes, then calls free() on that new location. This is a serious error.

CORRECTION: @keskiverto is correct: the pointer is incremented by 12 bytes.
Last edited on
1
2
3
p += 3;
// means
p = p + 3;

Now, the p is a pointer to long.
Pointer holds an address, so what address do we get when we add 3 to it?

Pointer to long. The +3 means here 3*sizeof(long) bytes.


Accessing array elements and "pointer math" are related:
1
2
3
4
long arr[7] = {9, 8, 7, 6, 5, 4, 3};
long one = arr[3];
long* p = arr;
long two = *(p + 3);

Both one and two do get the same value, 6, from the fourth element of the array.
Topic archived. No new replies allowed.