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

C program

Why segmentation fault? Explain

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

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

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, stain) ;
Printf(“%s”, str) ;

Expert Answer

 

#include <stdio.h>

#include <stdlib.h> /* malloc, free, rand */

void allocate_mem(char * str) {

str = (char *)malloc(20* sizeof(char)) ;

}

int main(){

FILE * stain;

char * str;

printf(“enter your input:”) ;

allocate_mem(str) ;

fgets(str, 20, stain) ;

printf(“%s”, str) ;

return 0;

}

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