I have a very simple program, a console application, that I wrote a long time ago under VS 2005 under XP. It worked perfectly OK. The program gets names and in the end prints them on the screen, until I do not enter a new name but only CR to finish the appplication.

Look at the listing below for reference.
After entering one or two names with length greater than 0, I press CR and expect the application to finish. It prints what it has to print but then gets stuck on delete [] names line. I simply have to close the command line window manually.
Any ideas why? It is driving me crazy!
The following print outs shows the results when it worked fully:

#include <iostream>
#include <string.h>
using namespace std;
#define _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES 1
//Program Name: Prog3_8 
//Location:C:\CENTRAL DATA BASE\Software\C++\C++ Moshe Haviv Book June 2008\Sources
// General Explanation: Usage of new for allocating memory from the heap
//  This is Prog3_6 with heap freeing
const int MAX = 50;//Up to 50 names on heap
int main()
{
char * names[MAX] ;//Only define string. No memory allocation yet
char inputName[80];
int num;
int l;
cout <<__FILE__ << '\n' << '\n' ;//__FILE__ is a predefined macro that prints the application name
cout << "Entering names\n";
    for( num=0; num <MAX; num++)
    {
    cout <<"Name:" ;
    cin.getline(inputName,80);// Get the string up to 79 characters long
    if(!strlen(inputName)) {break ;}//Continue only if input is not end(case agnostic)
    l = strlen(inputName);
    names[num] = new char[strlen(inputName) + 1];
    //Copy the entered name to the heap. We are using the more secure string copy strcpy_s instead of strcpy.
    strcpy_s(names[num],l+1, inputName);
    };
cout << "Here is the list of names you entered \n";
    for(int j=0; j<num; j++)
    {
    cout << names[j] << '\n';
    };
delete  [] names;
return 0;
}
//The output of the program:
/*
c:\users\mhaviv\documents\visual studio 2005\projects\why1\why1\prog3_6.cpp

Entering names
Name:Moshe
Name:Simba
Name:lola
Name:Me
Name:
Here is the list of names you entered
Moshe
Simba
lola
Me
Press any key to continue . . .

*/

Rather than using:
char *names[MAX];

do

char *names = new char[MAX];

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.