Question & Answer: Why segmentation fault? Explain…..

C program

Why segmentation fault? Explain

char * str;
Printf(“enter your input:”) ;
fgets(str, 20, stdin) ;
Printf(“%s”, str) ;

2. Does this code fix it? Why or why not. If no, write your own code below

Void allocate_mem(char * str) {
str = (char *) malloc (20* sizeof(char)) ;
}

Int main(){

char * str;
Printf(“enter your input:”) ;
allocate_mem(str) ;
fgets(str, 20, stdin) ;
Printf(“%s”, str) ;

Expert Answer

 

a. Segmentation fault is the condition where program crashes. The program results in segmentation fault. It is because here str is already defined and memory location is allocated to it. But it is again assigning memory location to str in fget. This is the reason the error occurs.

b. The given code does not fixes the problem. This is because again the memory is used for the char str and we are trysing to assign new memory to it. To fix the problem use the code:

#include <stdio.h>

void allocate_mem(char * str) {
str = (char *) malloc (20* sizeof(char)) ;
}

int main()
{
char * str;
char variable;

str = &variable;
printf(“enter your input:”) ;
allocate_mem(&variable) ;
fgets(&variable, 20, stdin) ;
printf(“%s”, &variable) ;

return 0;
}

Still stressed from student homework?
Get quality assistance from academic writers!