GATE | GATE CS Mock 2018 | Question 49
Consider the following code. The function myStrcat concatenates two strings. It appends all characters of b to end of a. So the expected output is “Geeks Quiz”. The program compiles fine but produces segmentation fault when run.
(i = 0; i <= n; i++)
a[m+i] = b[i];
Which of the following changes can correct the program so that it prints “Geeks Quiz”?
(A) char *str1 = “Geeks “; can be changed to char str1 = “Geeks “;
(B) char *str1 = “Geeks “; can be changed to char str1 = “Geeks “; and a line a[m+n-1] = ‘\0’ is added at the end of myStrcat
(C) A line a[m+n-1] = ‘\0’ is added at the end of myStrcat
(D) A line ‘a = (char *)malloc(sizeof(char)*(strlen(a) + strlen(b) + 1)) is added at the beginning of myStrcat()
Explanation: When str1 is declared as character pointer, it is stored in read-only block of memory so it can not be modified.
See following for a detailed explanation – https://www.geeksforgeeks.org/storage-for-strings-in-c/
Option (A) is correct.
Quiz of this Question
Level Up Your GATE Prep!
Embark on a transformative journey towards GATE success by choosing Data Science & AI
as your second paper choice with our specialized course. If you find yourself lost in the vast landscape of the GATE syllabus, our program is the compass you need.