SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Strings And Vectors
Exercise:
Self-test Exercises
Question:12 | ISBN:9780321531346 | Edition: 7

Question

What is the problem (if any) with this code?

char a_string[20] = "How are you? ";

strcat(a_string, "Good, I hope.");

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The code seems to be concatenating two strings using the strcat function. However, there is a potential issue with the code related to the size of the destination string a_string.

Let's break down the code:

char a_string[20] = "How are you? ";

Here, we declare a character array a_string with a size of 20 and initialize it with the string "How are you? " (including the null terminator '\0').

strcat(a_string, "Good, I hope.");

The strcat function is used to concatenate the string "Good, I hope." to the existing string a_string. The strcat function appends the source string to the end of the destination string.

The problem with this code is that the destination string a_string has a fixed size of 20 characters, including the null terminator. After the first initialization, the length of a_string is 14 (including the null terminator), leaving 6 characters of available space. However, the string "Good, I hope." is longer than 6 characters, so when strcat tries to concatenate the second string to the destination, it will exceed the array's bounds, leading to undefined behavior.

To fix this issue, we need to ensure that the destination string has enough space to accommodate both the initial string and the concatenated string. One way to do this is to make sure the destination string has enough space to hold the concatenated result.

Correct code:

char a_string[40] = "How are you? ";

strcat(a_string, "Good, I hope.");

 

0 0

Discussions

Post the discussion to improve the above solution.