Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can I Trust Memory Allocation?

I'm currently taking an introductory CS course that uses C. My textbook seems to imply that a pointer variable still holds the address for memory previously allocated to it, even after free() was called on it -- assume I previously used malloc(). Does this mean that portions of memory become "locked" when malloc() is called so the data of my pointer remains constant? What prevents other processes -- say google chrome or some app -- from messing with my variable? I could easily assign a value to an array at an invalid index, causing things to break. I could also access memory improperly, again using an array at an invalid index, giving me garbage or, if I'm really really lucky, a value that is meaningful to me. What is preventing a computer from spiraling into chaos!

like image 979
darylnak Avatar asked Dec 03 '22 22:12

darylnak


1 Answers

pointer variable still holds the address for memory previously allocated to it, even after free() was called on it

This is true. The situation is called "dangling pointer". Your program is not allowed to use these pointers; otherwise, its behavior is undefined.

Does this mean that portions of memory become "locked" when malloc() is called so the data of my pointer remains constant?

They are locked only in the sense that malloc would not return the allocated range to your program again, until you free it. There is no built-in protection, though: if your program accidentally writes to a freed pointer, it may overwrite data in a legitimate variable, leading to errors that are extremely hard to catch without proper tools.

What prevents other processes -- say google chrome or some app -- from messing with my variable?

The fact that other apps run in separate memory space. Hardware and OS ensure that other processes are locked out from the memory space of your program.

like image 82
Sergey Kalinichenko Avatar answered Dec 11 '22 12:12

Sergey Kalinichenko