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

692 views

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

In: Technology

5 Answers

Anonymous 0 Comments

In old languages like C and C++ it’s up to the programmer to not make mistakes. For example if you type:

int a[10];
a[16] = 0;

The first line gives you an array (like a group or collection) of 10 integers/numbers. The second line, you set the value of the 16th integer to 0. This doesn’t make sense, you asked for 10 numbers, you can’t set the value of the 16th number. In languages like C and C++ the is called undefined behaviour. What will happen, nobody knows. Your program might crash, it might act strangely, or it might work perfectly fine for 10 years and then start crashing.

Newer languages came along, and the designers said, people make mistakes, the language shouldn’t just allow it, but help them see their errors.

So in a newer language, if you type a[16] = 0; before it sets the value, it checks if position 16 is even valid. If not, it throws an error. Otherwise it sets the value. This check takes time, so people who like high performance have stuck with C and C++.

The other issue is sometimes the programmer doesn’t know how much memory is needed. For example, if you are creating an image editor, you don’t know the size of the image the user will open. So you need to wait until they open it, look and the width and the height an the request enough memory to hold the image. Something like:

auto image = new Pixel[width * height];

and then when the programmer is done with the memory:

delete[] image;

Again, it’s up to the programmer to not ask for a pixel at a position outside of the image. Or to ask for a pixel after they’ve already deleted the image.

Go takes a different approach. The programmer still has to ask for the data for the image, but they don’t have to worry about deleting it later. Instead, the language, every few milliseconds, looks at all the memory being used, and can see if the image data won’t be used again and deletes it for the programmer. The downside here is this checking takes time, and the program will be using memory it no longer needs, but go hasn’t noticed it can free it yet.

Most programmers use safer languages now, they are a little slower, but it’s not an issue for most things, maybe other than operating systems and video games.

So Rust came along and took a different approach. It’s goal is to be fast and safe. Also, if you are going to write an operating system, you need to be able to poke around in memory in weird and unsafe ways. So it has unsafe blocks, you can write all you weird and crazy code in there and do anything. The rest of the program will be safe. The advantage here is if you do have a crash, you only need to look in the few unsafe spots and check them carefully, compared to C++ where the crash could be anywhere.

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