C | String | Question 1
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.
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: In the above program “Geeks ” and “Quiz” stored in read-only location but the line a[m+i]=b[i] tries to write a read only memory. The problem can be solved by storing str in writable stack segment. For more details see following. https://www.geeksforgeeks.org/storage-for-strings-in-c/
Quiz of this Question