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.
void myStrcat(char *a, char *b) { int m = strlen(a); int n = strlen(b); int i; for (i = 0; i <= n; i++) a[m+i] = b[i]; } int main() { char *str1 = "Geeks "; char *str2 = "Quiz"; myStrcat(str1, str2); printf("%s ", str1); return 0; } |
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[100] = “Geeks “;
(B) char *str1 = “Geeks “; can be changed to char str1[100] = “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()
Answer: (A)
Explanation: Option (A) is correct.
See following for explanation.
http://www.geeksforgeeks.org/storage-for-strings-in-c/
Quiz of this Question
Recommended Posts:
- GATE | GATE CS Mock 2018 | Set 2 | Question 43
- GATE | GATE CS Mock 2018 | Set 2 | Question 44
- GATE | GATE CS Mock 2018 | Set 2 | Question 45
- GATE | GATE CS Mock 2018 | Set 2 | Question 46
- GATE | GATE CS Mock 2018 | Set 2 | Question 47
- GATE | GATE CS Mock 2018 | Set 2 | Question 58
- GATE | GATE CS Mock 2018 | Set 2 | Question 59
- GATE | GATE CS Mock 2018 | Set 2 | Question 60
- GATE | GATE CS Mock 2018 | Set 2 | Question 61
- GATE | GATE CS Mock 2018 | Set 2 | Question 62
- GATE | GATE CS Mock 2018 | Set 2 | Question 63
- GATE | GATE CS Mock 2018 | Set 2 | Question 64
- GATE | GATE CS Mock 2018 | Set 2 | Question 65
- GATE | GATE CS Mock 2018 | Set 2 | Question 57
- GATE | GATE CS Mock 2018 | Set 2 | Question 56



