Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outside allocated space in C

Well, I always think that if I call malloc function, I assign specific amount of memory, but, I've just realised that if I write:

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

I can assign a value to a[4] or any another index, I though that, in this case, I could only assign to a[0] or a[1]. What's the concept error I have?

like image 883
German Avatar asked Feb 22 '23 05:02

German


2 Answers

When you write a[4], it is the same as writing *(a + 4). Since the compiler doesn't know how much memory is allocated at the address that a points to, it will happily let you address the memory.

However, the memory located there could be anything - it could be another variable used by your program, part of the stack, or just out of the bounds of your program. Accessing outside the allocated space in this way is likely to (at best) produce a segmentation fault or (at worst) introduce a security hole by overwriting other parts of your program.

You are correct in that you can only assign to a[0] or a[1] safely, but the C compiler will let you assign outside that bounds (because it doesn't know any different).

It is not safe to do a[4] in your example.


Also, it is better not to cast the result of malloc - see this answer

like image 56
Timothy Jones Avatar answered Feb 23 '23 18:02

Timothy Jones


In C, there is no way to check for array overflow. You can go on write beyond the array, until you enocunter writing to an invalid address or a read-only page etc.

There are some tools available which makes you detect immediately, as an when you cross the array boundary. NJAMD is one such tool, where it makes the immediate memory location beyond array boundary as read-only.

As an when you access a read-only memory, it gives SIGSEGV. so you can detect immediately an array overflow.

like image 21
vamsi Avatar answered Feb 23 '23 18:02

vamsi