Sign in with Google to keep private notes

Allocating Space

  • Code segment (Read only)
  • BSS segment (uninitialised data/explicitly default value initialisd (0, or 0x0 etc)
  • Data segment (initialised data)
  • Heap (Dynamically allocated variables)
  • Call stack (Function params, where most of the local variables lie)

Matters because compiler can perform BSS optimisation to save space in executable (you dont need to initially make space for all those 0s (Imagine a very long 0 initialised array))

Recall stack pointers (register that keeps track of the top of the stack) and stack frames (a bunch of bytes on the stack corresponding to a function call)

What to shove in stack frame:

  1. New variables

  2. Overwritings of new variables

  3. The eventual return value

  4. Arguments to the function

Then pop it off at the end

The code for stackoverflow is: -1073741571

Memory API chapter 14:

When would i ever use the heap?

Need Example
Data must outlive the function that creates it<br>(If its on the stack it gets pop when the function is over) Creating an object and returning a std::unique_ptr to it
Storage needs to grow at runtime A std::vector growing as you insert elements
Data is too large for the stack An array containing millions of elements

Here's an excerpt from OSTEP 14.4 i found kind of interesting. (Note that in C you should malloc(strlen(original))) + 1; to make this work.

Oh wait while Im on the subject, malloc returns a pointer to a void type. Then the void type has to be casted by the C programmer because people who code in C hate themselves.

Not Allocating Enough Memory

A related error is not allocating enough memory, sometimes called a buffer overflow. In the example above, a common error is to make almost enough room for the destination buffer.

char src = "hello"; 
char dst = (char *) malloc(strlen(src)); // too small! 
strcpy(dst, src); // can still work properly 

Oddly enough, depending on how malloc is implemented and many other details, this program will often run seemingly correctly. In some cases, when the string copy executes, it writes one byte too far past the end of the allocated space, but in some cases this is harmless, perhaps overwriting a variable that isn’t used anymore. In some cases, these overflows can be incredibly harmful, and in fact are the source of many security vulnerabilities in systems.

In other cases, the malloc library allocated a little extra space anyhow, and thus your program actually doesn’t scribble on some other variable’s value and works quite fine.

In even other cases, the program will indeed fault and crash. And thus we learn another valuable lesson: even though it ran correctly once, doesn’t mean it’s correct.

A valuable life lessson indeed.

Ok actually all of these life lessons are kind of interestring im just gonna list them out. The last few w/o parantheiss just seem like general programming errors, nothing specifically to do with the memory API

  1. Forgetting to allocate memory (imagine strcpy into something with no memory): SEG FAULT
  2. Not allocating enough memory (see above)
  3. Free memory prematurely (lol then someone else take the memory and screw you over)
  4. Calling free twice (this is UB??? damn)
  5. Passing normal variables you didn't get from malloc to free (was C designed to maximise suffering?)
  6. Never free memory ohor i tell teacher
  7. Not initialising your allocated memory

"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off"

Oh also memory leaking is fine for short programs since they end quick enough that the OS can reclaim everything. Two people have to worry about memory leaks

  1. Server writers (or any kind of long running process)

  2. Kernel writers

A second performance critical reason why x->foo() is slower than y.foo()

This is the other reason, but I wouldn't expect someone to think about this on-the-spot. The stack-allocated object y is usually close to the current stack frame and often resides in the CPU cache. The heap-allocated object x might be in a different region of memory, possibly leading to more cache misses or less predictable locality. This effect can dominate in performance-critical or memory-intensive programs.

It's closer to the stack pointer so its probably in the cache. Cool.

C++ storage and linkage

Storage

There are 4 types: Global, static, thread, dynamic. Only thread is that big of a deal

#include <memory>
#include <thread>

int global = 10;                 // STATIC: storage lasts for the entire program.
thread_local int perThread = 0;   // THREAD: each thread has its own independent int.

void example()
{
    int local = 10;              // AUTOMATIC: a fresh int each call; gone on return.

    static int calls = 0;        // STATIC: the same int persists between calls.
    ++calls;                    // Becomes 1, then 2, then 3 across successive calls.

    ++perThread;                // Changes only the calling thread's copy.

    int* p = new int{10};        // DYNAMIC: the allocated int lasts until deleted.
                                // p itself is an AUTOMATIC local pointer.
    delete p;                   // Releases the dynamically allocated int.

    auto q = std::make_unique<int>(20);
                                // DYNAMIC int owned by an AUTOMATIC smart pointer.
}                               // local, p, and q are destroyed.
                                // q automatically deletes its dynamic int.
                                // calls and perThread remain.

int main()
{
    example();                  // calls = 1; main thread's perThread = 1.
    example();                  // calls = 2; main thread's perThread = 2.

    std::thread worker(example);
                                // calls = 3; worker's separate perThread = 1.
    worker.join();              // Waits for worker; its perThread dies at thread exit.
}                               // Program ends; static storage is released.

Linkage

Most variables as I normally write them fall under "No linkage". That means: Cannot be referred to outside of this scope.

// ===== a.cpp =====

int shared = 10;         // EXTERNAL: other files can refer to this variable.
static int privateX = 20; // INTERNAL: this name belongs only to this file.
void example()
{
    int local = 30;      // NO LINKAGE: a local name inside this function.
}

We showed last time article that -O2 compiler optimisation allows compiler folding of a declared but undefined function. And we said this was because the compiler could be sure the function is not called in other translation units. So here's the explanation as to why: static variables have explicitly internal linkage

// ===== b.cpp =====

extern int shared;      // Refers to the variable defined in a.cpp.
                        // Does NOT create another int.

static int privateX = 99; // A separate variable. No clash with a.cpp's privateX.

Cool.

If you define variables outside of function declarations they default to static storage duration and external linkage. These are global variables. Remember: They are global TO EACH FILE.

Then when you want two global variables with the same name in 2 seperate translation units, thats when you have to kick in the static keyword. The static keyword will give it internal linkage, but with or without the keyword it would have had static storage duration. I am confused.

this is also achievable by wrapping in an anonymous namespace (i dont actually know what this means)

namespace {
    Value v{42};
}

const implies internal linkage and if you want it referrabloe outside then you have to use extern const

Thread local variables might be used when you want a shared global state, but keep it only for a given thread and thus avoid synchronization issues. To simulate such behavior and understand those types of variables, we can create a map of variables:

std::map<thread_id, Object> objects;
objects[std::this_thread::get_id()] = x; // modify the global object...

ok im not processing any of this i will be back later

Articles to read next