57.9k views
5 votes
Consider the following declaration of a C-string variable, where SIZE is a defined constant: char myString[SIZE]; The C-string variable myString has been assigned in code not shown here. For correct C-String variables, the following loop reassigns all positions of myString the value of 'Z' , leaving the length the same as before. Assume this code fragment is embedded in an otherwise complete and correct program. Please provide answers to the two questions following this code fragment. int index = 0; while (myString [index] != '\0') { myString[index] = 'Z'; index++; } (a) Explain how this code can destroy the contents of memory beyond the end of the array. (b) Modify this loop to protect against inadvertently changing memory beyond the end of the array.

User Thegauraw
by
7.5k points

1 Answer

5 votes

Final answer:

The code can cause memory corruption if the C-string is not null-terminated by overwriting memory past the array. The loop is modified to include an index boundary check to prevent such overflow and protect the integrity of memory.

Step-by-step explanation:

The given code segment is intended to replace all characters in a C-string with the character 'Z', without changing the string's length. However, the provided code can destroy the contents of memory beyond the end of the array if myString is not null-terminated, which is a common precondition for C-string manipulation functions. If myString lacks a null-terminator (the '\0' character), the while loop will continue iterating past the end of the allocated array since the condition myString[index] != '\0' will never become false, leading to undefined behavior and potentially overwriting memory that lies beyond the array.

To prevent this potential overflow, the loop needs to also check that the index does not exceed the bounds of the array. Here is a modified loop that adds this check:

int index = 0;
while (index < SIZE - 1 && myString[index] != '\0') {
myString[index] = 'Z';
index++;
}

This addition ensures that the loop terminates if it reaches the end of the allocated space for myString, regardless of the presence of a null-terminator, therefore protecting against changing memory beyond the end of the array.

User SeanC
by
8.5k points