1.

What are the reasons for segmentation fault in Embedded C? How do you avoid these errors?

Answer»

Following are the reasons for the segmentation fault to occur:

  • While trying to dereference NULL POINTERS.
  • While trying to write or update the read-only memory or non-existent memory not accessible by the program such as code segment, kernel structures, etc.
  • While trying to dereference an uninitialized pointer that MIGHT have been pointing to INVALID memory.
  • While trying to dereference a pointer that was recently freed using the free function.
  • While accessing the array beyond the boundary.

Some of the ways where we can avoid Segmentation fault are:

  • Initializing Pointer PROPERLY: Assign addresses to the pointers properly. For instance:
    • We can also assign the address of the matrix, vectors or using functions like calloc, malloc etc.
    • Only important thing is to assign value to the pointer before accessing it.
int varName;int *p = &varName;
  • MINIMIZE using pointers: Most of the functions in Embedded C such as scanf, require that address should be sent as a parameter to them. In cases like these, as best practices, we declare a variable and send the address of that variable to that function as shown below:
int x; scanf("%d",&x);

  In the same way, while sending the address of variables to custom-defined functions, we can use the & parameter instead of using pointer variables to access the address.

int x = 1; x = customFunction(&x);
  • Troubleshooting: Make sure that every component of the program like pointers, array subscripts, & operator, * operator, array accessing, etc as they can be likely candidates for segmentation error. Debug the statements line by line to identify the line that causes the error and investigate them.


Discussion

No Comment Found