Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Which of the following programs will cause segmentation faults? Why? (1) #includ

ID: 3719183 • Letter: W

Question

Which of the following programs will cause segmentation faults? Why?

(1)

#include<stdio.h>

#include<stdlib.h>

  

int main(void)

{      char *p = malloc(3);

  

     *p = 'a';

     *(p+1) = 'b';

     *(p+2) = 'c';

  

     free(p);

  

     *p = 'a';

  

     return 0;

}

(2)

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main(void)

{

char *p ;

strcat(p, "abc");

printf(" %s ", p);

return 0;

}

(3)

#include<stdio.h>

#include<stdlib.h>

  

int main(void)

{

     char *p = (char *) main;

     printf("The first byte of main() is %c ", *p);

     *p = "Hello";

     printf("The first byte of main() is %c ", *p);

     return 0;

}

Explanation / Answer

Program Number 3 contains Segmentation Fault.

#include<stdio.h>

#include<stdlib.h>  

int main(void)

{

     char *p = (char *) main;

     printf("The first byte of main() is %c ", *p);

     *p = "Hello";

     printf("The first byte of main() is %c ", *p);

     return 0;

}

Cause of segmentation fault on statement *p = "Hello";

The value of *p before executing the statement *p = "Hello"; is [ 0x400536 <main> "UH‰åHƒìHÇEø6@" ]
and the first printf statement prints the character "U" which is after <main> 1st character.

the segmentation faults occurs because of assignment makes integer from pointer without a cast [-Wint-conversion]      *p = "Hello"; due to this program terminated with signal SIGSEGV, Segmentation fault.

SIGSEGV : A SIGSEGV is an error(signal) caused by an invalid memory reference . You are probably trying to access an array element out of bounds or trying to use too much memory.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote