Programming/C/Memory Model

From Dev Wiki
< Programming‎ | C
Revision as of 19:15, 22 April 2023 by Brodriguez (talk | contribs) (Import memory sections for C++ page)
Jump to navigation Jump to search

Both C and C++ force the programmer to manage pointers and memory.


This is a manual process. This is also both a blessing and a curse.


On one hand, the programmer can potentially manage references and variable/object deconstruction (aka, what many languages refer to as "garbage collection") much better than any language that has garbage collection built-in and handled automagically.
In other words, a given C/ C++ program can potentially be magnitudes more efficient.

On the other hand, if not careful, or if they don't know what they're doing, a programmer can introduce many bugs and unintentional problems by incorrect manual garbage collection.
A set of memory can be allocated that's too small. So memory references overlap and garble data. Or data can be forgotten about, potentially hanging in memory and taking up space far far longer than it would have been around with automatic garbage collection.


Pointers and memory management is one of the biggest differences between C/C++ and any other language.


Computer Memory

A computer's memory is a series of locations called addresses. Each memory address:

  • Can contain a set amount of data, represented as a given amount of 1's and 0's.
  • Is represented with a unique identifier number.
ToDo: Document binary, at least basics.

The 1's and 0's are called Binary. The computer automatically converts data to binary to store it in memory, and then back to the original format, so we as humans can understand it.
Similarly, the computer will automatically determine the unique identifiers that correspond to each address space.
So while it's potentially useful to understand these underlying concepts, we as programmers don't (usually) need to directly deal with these concepts.


Note: For very large pieces of data, we can chain together memory addresses to store more information. Thus, addresses defined by pointers have varying sizes.
This is how one can make addresses overlap.

For example, let's say a programmer makes two sequential int address pointers. So we have ... | open memory | int pointer #1 | int_pointer #2 | open memory |....

Normally, one assigns a standard integer value to each location and this is fine. HOWEVER, if one assigns a larger data type to "int pointer #1", then it will overflow into the address space of "int pointer #2", overriding any bits that might have already been there.
Furthermore, if this other data type is somehow excessively large, it might overflow enough that it continues on past the entirety of "int pointer #2", and overrides even more memory address space.