4. (10 points) Below is a simple test program for testing a copy function #inclu
ID: 3715698 • Letter: 4
Question
4. (10 points) Below is a simple test program for testing a copy function #include stdio . h> #include #include char copier (char* src) char* tmpmalloc (strlen (sr)+1); strncpy (tmp, src , strlen (src)+1); return tmD: int main (int argc, char argv) char copy copier (argv [1]); printf("input: %s copy : %s ".argv[1].copy); return 0 The test program above produces the correct output and seems to runs without issues However, when the copy function is deployed to a production server the server crashes after running for a few hours a) Where in memory is the tmp string stored? (b) Why does the test appear correct, but the server crash? c) What could you do to fix the problem?Explanation / Answer
Solution:
a)
This is a dynamic memory allocation wherein the memory is allocated to the variable temp which is of char type which holds a string.
b)
Because of the source string is copied to the destination string completely, that is why it is working correctly.
The server is crashing because one extra memory block is getting accessed by strcpy next to where the string src is allocated, which does not belong to the string src.
so the server crashed in order to avoid buffer underflow/overflow.
c)
change the strncpy to
strcpy(temp, src)
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.