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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.