what makes programming languages like go and rust memory-safe and c++ not?

693 views

what makes programming languages like go and rust memory-safe and c++ not?

In: Technology

5 Answers

Anonymous 0 Comments

Languages like C++ and C allow you to handle memory allocation yourself.

This means you have the power of managing when an object gets created in memory and when it gets destroyed. It’s a wonderful thing, since it gives you complete freedom. It’s also a curse, because you must make sure that you know what you’re doing.

If you allocate memory for an object and you never free it, you create a **memory leak**. If you do this repeatedly (even worse: in a loop) you can easily hog memory until the program crashes down with the rest of the system.

If you free memory for an object, but you keep pointing to its old location in memory, you created a **dangling pointer**. Trying to access that means crashing the program, in the best of cases. Trying to deallocate the object a second time results in a **double free** – again, with dire consequences.

If you allocate a certain block of memory for an object, but you keep reading well past it, you end up accessing memory that you shouldn’t. This can result in more than crashing your program: you can pave the way for the next vulnerability to be exploited by a malicious user (**buffer overflow** attack). In C++, and even more in C, this is dangerously easy to do simply by operating on strings and forgetting to put a terminator character at the end.

Higher level languages don’t allow you to this do kind of damages. They employ boundary checks to avoid buffer overflows.

They might use a **garbage collector** – you can see it like a little program inside your program, constantly overseeing memory and automatically freeing memory when it’s no longer used.

In short, they take away the power to manage memory yourself – depending on the cases, this can come at a cost in terms of performance. But in exchange they give you the safety of not shooting yourself in the foot.

You are viewing 1 out of 5 answers, click here to view all answers.