How Can I Use C Code to Read Random Section of Memory
by Tiago Antunes
How to understand your program'southward memory
When coding in a linguistic communication like C or C++ you can interact with your memory in a more depression-level way. Sometimes this creates a lot of bug you didn't go before: segfaults. These errors are rather annoying, and can crusade you a lot of trouble. They are oft indicators that you lot're using retention you shouldn't apply.
1 of the most common bug is accessing retention that has already been freed. This is retention that you've either released with free, or memory that your plan has automatically released, for instance from the stack.
Agreement all this is really simple and it will definitely make y'all program better and in a smarter way.
How is the memory divided?
Memory is divided in multiple segments. Two of the nearly important ones, for this mail service, are the stack and heap. The stack is an ordered insertion place while the heap is all random — you allocate memory wherever yous can.
Stack memory has a prepare of means and operations for its piece of work. It's where some of your processor'due south registers data gets saved. And it's where relevant data most your programme goes — which functions are called, what variables you lot created, and some more information. This retentivity is also managed by the program and not by the developer.
The heap is often used to allocate big amounts of memory that are supposed to exist as long every bit the developer wants. That said, it's the developer's chore to control the usage of the memory on the heap. When building complex programs, you ofttimes need to classify large chunks of memory, and that's where yous use the heap. We call this Dynamic Retentivity.
You're placing things on the heap every fourth dimension you use malloc to allocate memory for something. Any other phone call that goes like int i; is stack retention. Knowing this is really of import so that yous tin can hands find errors in your program and farther improve your Segfault error search.
Understanding the stack
Although you may not know about it, your program is constantly allocating stack memory for it to work. Every local variable and every part you phone call goes there. With this, you can do a lot of things — most of them are things that you did not want to happen — like buffer overflows and accessing incorrect memory.
So how does it really work?
The stack is a LIFO (Last-In-Outset-Out) data structure. You can view it as a box of perfectly fitted books — the last book yous place is the first one y'all take out. By using this structure, the plan tin can easily manage all its operations and scopes by using two simple operations: push and popular.
These two practise exactly the contrary of each other. Push inserts the value to the tiptop of the stack. Pop takes the summit value from it.
To keep track of the current memory identify, there is a special processor register chosen Stack Pointer. Every time you need to save something — like a variable or the return address from a function — information technology pushes and moves the stack pointer up. Every time you lot exit from a function, it pops everything from the stack pointer until the saved return address from the role. Information technology's unproblematic!
To test if yous understood, let'southward utilize the following instance (attempt and find the bug solitary ☺️):
If yous run it, the program will simply segfault. Why does this happen? Everything looks in place! Except about… the stack.
When we telephone call the function createArray, the stack:
- saves the render address,
- creates
arrin stack memory and returns it (an array is merely a arrow to a memory location with its data) - simply since we didn't apply
mallocit gets saved in stack retention.
After we return the pointer, since we don't take whatsoever control over stack operations, the program pops the info from the stack and uses it equally information technology needs. When nosotros try to fill in the array after we returned from the role, we corrupt the memory — making the program segfault.
Agreement the heap
In opposition to the stack, the heap is what you use when you want something to be for some time independently of functions and scopes. To use this memory, the C linguistic communication stdlib is really good every bit it brings ii awesome functions: malloc and free.
Malloc (memory allocation) requests the system for the corporeality of retentivity that was asked for, and returns a pointer to the starting address. Gratis tells the system that the retentivity we asked for is no longer needed and tin be used for other tasks. Looks actually simple — as long as you avoid mistakes.
The system can't override what developers asked for. And then it depends on us, humans, to manage information technology with the 2 functions above. This opens the door for i human error: Memory Leaks.
Memory Leak is memory that was requested by the user that was never freed — when the program ended or pointers to its locations were lost. This makes the program use much more memory than what information technology was supposed to. To avoid this, every fourth dimension we don't need an heap allocated element anymore, we gratuitous it.
In the picture above, the bad fashion never frees the retention we used. This ends upwardly wasting 20 * 4 bytes (int size in 64-bit) = 80 bytes. This might not look that much, just imagine non doing this in a behemothic program. We can end up wasting gigabytes!
Managing your heap memory is essential to make your programs retentiveness efficient. Just you also need to be conscientious on how you lot employ it. Simply similar in stack retentiveness, after the memory is freed, accessing it or using information technology might cause you a segfault.
Bonus: Structs and the heap
One of the common mistakes when using structs is to merely free the struct. This is fine, as long as we didn't allocate retentiveness to pointers inside the struct. If memory is allocated to pointers inside the struct, we first need to gratuitous them. And then we tin free the unabridged struct.
How I solve my memory leak bug
Most of the time when I program in C I'm using structs. Therefore I always take two mandatory functions to use with my structs: the constructor and the destructor.
These two functions are the only ones where I use mallocs and frees on the struct. This makes it really unproblematic and easy to solve my memory leaks.
(If y'all would like to know more about making code easier to read, check my post on abstraction).
A keen memory direction tool — Valgrind
Information technology's hard to manage your memory and make sure that you handled everything correctly. A great tool to validate if your program is behaving correctly is Valgrind. This tool validates your programme, telling you lot how much memory yous allocated, how much was freed, if you tried to write in an incorrect memory area… Using it is a great way to validate if everything is ok, and 1 should utilize it to avoid security compromises.
Don't forget to follow me!
Besides posting hither on Medium, I'm also on Twitter.
If you lot have any questions or suggestions, don't hesitate to contact me.
Larn to lawmaking for costless. freeCodeCamp's open source curriculum has helped more than 40,000 people go jobs as developers. Go started
Source: https://www.freecodecamp.org/news/understand-your-programs-memory-92431fa8c6b/
0 Response to "How Can I Use C Code to Read Random Section of Memory"
Post a Comment