Safe functions in the D ensure memory safety by using safe values, operations, and interfaces inside their body. The @safe
keyword marks these functions.
Here are some important points we should note about safe functions in D:
Let use the famous problem of printing "Hello World" in C. The code for printing "Hello World" is given below, where printf
is used for printing a string of characters.:
#include<stdio.h>int main() {printf("hello, world\n");return 0;}
printf
The following code snippet shows the signature of printf
accepting several arguments of different types. The details of these arguments are encoded in the format string. Thus, printf
is a variadic function, where ...
represents optional parameters. It it can take an indeterminate number of arguments.
int printf (const char * restrict format, ...);
Let's understand this concept using the code below, which prints different combinations of strings and integers. The following code explains that printf
needs at least one string argument followed by 0 or more arguments of different types, the details of which are encoded in format
:
#include<stdio.h>int main() {char myString[ ] = "hello World";int myInt = 0;printf("This is a string: %s", myString);printf("\nThis is a string: %s and an int: %d", myString, myInt);return 0;}
printf
is unsafe in CHere are some reasons why printf
is unsafe in C:
printf
with too few arguments does not always give a warning but, as per standard C guidelines, it can result in undefined behavior. * format
also violates the principle of memory safety. In the above example, * format
points to a null-terminated string. So, it does not result in compromised code. Thus, the programmer must ensure that any pointer should point to a valid piece of data.
Now let's see an equivalent safe function in D:
import std.stdio;void main(){writeln("Hello, World!");}
writeln
is safe in DHere are some reasons why writeln
is safe in D:
writeln
is ensured at compile-time using code templates while dealing with a variable number of arguments using tuples.writeln
is called with a single string type argument. Strings in D are not pointers, but immutable char
arrays (a safe subset of D). Here are some limitations of safe functions in D:
Free Resources