Question
Consider the following C code snippet. /* Escapes all newlines in the input string, replacing them with . */ /* Requires: p != NULL;
Consider the following C code snippet.
/* Escapes all newlines in the input string, replacing them with " ". */
/* Requires: p != NULL; p is a valid \0-terminated string */
void escape(char *p)
{
while (*p != \0)
switch (*p)
{
case :
memcpy(p+2, p+1, strlen(p));
*p++ = \\; *p++ = n;
break;
default:
p++;
}
}
Question! You may assume that escape()'s argument is always non-null and points to a \0-terminated string. What's wrong with this code?
Hints:
The code '\0' terminates the string so the while statement reads each character until it reaches \0. The memcpy statement is "making room" for the to be inserted.
*p++ = '\\'; inserts a backslash \
*p++ = 'n'; inserts the n
p++; moves to the next character in the string. NOTE: The important fact here is that C++ does not detect when memory is overflowed (or underflowed).
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started