DEV Community

Discussion on: Explain "Memory Safe Programming Languages" Like I'm Five Please

Collapse
 
e1mer profile image
Elmer

Let's say I want to copy a string.

In unsafe languages the string ends with a "special" character.

In the C language strings end with the ASCII nul character. AKA the number 0.

If you don't put a NUL in your string you just keep copying past the space it was supposed to go in.

In a memory safe language the language enforces memory boundaries.

In the C programming language, for example, the string copy function strcpy() copies a string up to the NUL. It hopes there is one.

A different function, strncpy() includes the maximum number of characters you can copy, and stops if you try to exceed that number.

Note: the string returned is not NUL terminated if you go to far.

This kind of checking happens for every memory operation.

C has a memory safe copy (strncpy), but it's not mandatory, so the entire language is not memory safe, even tho you coulf write memory safe programs in it.