Hi, this is a code for Simple Console based text editor from Complete Reference to C++ by Herbert Shildt:

#include "stdafx.h"
#include "conio.h"

#define MAX 5
#define LEN 20
char text[MAX][LEN];

int _tmain(int argc, _TCHAR* argv[])
	register int t, i, j;
	printf("Enter an empty line to quit.\n");

	for(t=0; t<MAX; t++) 
		printf("%d: ", t);
		if(!*text[t]) break; /* directly hiting Enter key appends '\0' i.e. null, hence &text[t] will be null;  quit on blank line */  
	for(i=0; i<t; i++) 
		for(j=0; text[i][j]; j++)

	return 0;

I insert a letter 'a' 20 times on first line:

& then 'b' 20 times:
{image: http://img59.imageshack.us/i/29952735.png/}

but at first, it stores 'a' correctly:
{image: http://img141.imageshack.us/i/79038161.png/}

however for second iteration, it stores the 'b's incorrectly:
[image: http://img689.imageshack.us/i/80327231.png/]

this continues further, if I enter 'c' 20 times & so on.

The final output is also wrong:
[image: http://img3.imageshack.us/i/49207766.png/]

However the code works great for small strings:
[image: http://img822.imageshack.us/i/31994060.png/]
Why is this overlapping?

Please help.

Your array has 20 columns. When you use puts to read a string, it puts a null character ('\0') at the end of its input. So if your input is 19 characters or longer, the input (including the null character) runs off the end of the row of the array and onto the next row.

So this program fails any time it gets more than 19 characters of input.

More generally, this failure is an unavoidable aspect of using gets: The gets function takes a pointer to memory, and simply overwrites as much memory as necessary to hold its input. Because you don't know how much input you're going to get, you don't know how much memory it is going to overwrite.

As a consequence of this behavior, you should never use gets in your programs for any reason. Because it overwrites memory unpredictably, any program that uses gets has security problems that are impossible to fix. For that reason, I think that if you are using a book that recommends the use of gets, you should consider using a different book.

This article has been dead for over six months. Start a new discussion instead.