C/C++: Why C and C++ are so Dangerous Languages?

The article highlights the risks of programming in C, emphasizing issues like lack of bounds checking and the potential for memory safety errors. It underscores the responsibility of programmers to manage memory carefully to avoid undefined behavior and security vulnerabilities.

Why is C so Dangerous?

C is a hazardous language since it permits you to perform tasks that entrance memory past what has been distributed.

For instance, you can have a variety of numbers with 400 bytes assigned to it, however it is feasible to file it, map the 1000th byte of that exhibit, and afterward access that memory.

Is astounding that the GCC compiler produces no mistakes or alerts about this; it will incorporate your code easily, despite the fact that running such a program might cause crashes or unknown way of behaving.

You might ponder, “For what reason am I composing code like this?” You might feel that you wouldn't purposefully pick something taboo.

Notwithstanding, in the event that client input, like information from the Web, decides the file -, for example, getting a record worth of 1000 and setting ‘array[i]' to some esteem – this can prompt memory defilement.

This is a typical reason for some bugs, on the grounds that the C language has no innate system to forestall access or change of memory beyond a designated exhibit.

Example of Code

This is a very basic example, but it demonstrates that:

#include <stdio.h>

int main() {
    // Allocate an array of 100 integers (400 bytes)
    int array[100];
    
    // An out-of-bounds index
    int index = 1000; 

    // Attempt to set the value at the out-of-bounds index
    array[index] = 99; // Undefined behavior

    // Print a message to indicate what happened
    printf("Set array[%d] to 99.\n", index);

    return 0;
}

Conclusion

In conclusion, here are some key topics we learned:

1. Memory Safety in C: C allows direct memory manipulation, which can lead to accessing memory outside of allocated bounds, causing undefined behavior.

2. Lack of Bounds Checking: C compilers like GCC do not automatically check for out-of-bounds array accesses, placing the responsibility on the programmer.

3. Undefined Behavior: Accessing memory outside the allocated bounds can result in crashes or other unpredictable behaviors.

4. Security Vulnerabilities: Out-of-bounds access, especially when influenced by external inputs, can lead to memory corruption and potential security vulnerabilities.

@freecoder
@freecoder

With 15+ years in low-level development, I'm passionate about crafting clean, maintainable code.
I believe in readable coding, rigorous testing, and concise solutions.

Articles: 29