Razones por las que falla un programa en C++

A veces nos encontramos con bloqueos anormales de programas C++. A continuación se presentan algunas razones posibles que pueden causar que C++ se bloquee de manera anormal.

  • Segmentation Fault: It is the major reason for program to crash. These are may be the reasons for the such cause:
    • Attempting to access memory location that doesn’t exist in our system.
    • There may be an attempt to write on a read only memory location.

      // CPP program to demonstrate
      int main()
      {
         char *str; 
         
         /* Stored in read only part of data segment */
         str = "GfG";     
         
         /* Problem:  trying to modify read only memory */
         *(str+1) = 'n'
         return 0;
      }

      Output :

      Segmentation fault (core dumped)
    • There may be an attempt to access protected memory location such as kernel memory
    • Stack Overflow: There may case of non terminating recursion with memory location.

      // C program to demonstrate stack overflow
      // by creating a non-terminating recursive
      // function.
      #include<stdio.h>
        
      void fun(int x)
      {
          if (x == 1)
             return;
          x = 6;
          fun(x);
      }
        
      int main()
      {
         int x = 5;
         fun(x);
      }

      Output :

      Segmentation fault (core dumped)
  • Buffer Overflow: It is an anomaly where a program, while writing data to a buffer, overruns the buffer’s boundary and overwrites adjacent memory locations.

    • Consider below C++ program.

      // C++ code to demonstrate buffer
      // overflow.
      #include <bits/stdc++.h>
      using namespace std;
        
      // driver code
      int main()
      {
          char A[8] = "";
          unsigned short B = 1979;
          strcpy(A, "excessive");
          return 0;
      }

      Output :

      *** stack smashing detected ***: /home/gfg/a terminated
      Aborted (core dumped)

      The program has two variables which are adjacent in memory: an 8-byte-long string buffer, A, and a two-byte big-endian integer, B.

      char A[8] = “”;
      unsigned short B = 1979;

      Initially, A contains nothing but zero bytes, and B contains the number 1979.

      Now, the program attempts to store the null-terminated string “excessive” with ASCII encoding in the A buffer.

      strcpy(A, “excessive”);

      This string is of 9 characters long and encodes to 10 bytes including the null terminator, but A can take only 8 bytes. By failing to check the length of the string, it also overwrites the value of B:

      B’s value has now been inadvertently replaced by a number formed from part of the character string. In this example “e” followed by a zero byte would become 25856.

      This overflow is called buffer buffer overflow.

  • Fuga de memoria:
    Si asignamos algo de memoria por algún programa y lo dejamos como está. Después de un tiempo, habrá una gran cantidad de memoria asignada pero no utilizada, por lo que faltará memoria después de un tiempo. Y así el programa comienza a fallar.

    // C program to demonstrate heap overflow
    // by continuously allocating memory
    #include<stdio.h>
       
    int main()
    {
        for (int i=0; i<10000000; i++)
        {
           // Allocating memory without freeing it
           int *ptr = (int *)malloc(sizeof(int));
        }
    }
  • Excepciones
    • Dividir entre cero.

      // C++ code to demonstrate divide by 0.
      #include <bits/stdc++.h>
      using namespace std;
        
      // driver code
      int main()
      {
          int x = 10;
          int y = 0;
          cout << x/y;
          return 0;
      }

      Producción :

      Floating point exception (core dumped)

Publicación traducida automáticamente

Artículo escrito por akash1295 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *