0

So this is my code:

#include "stdafx.h"
#include <iostream>

using namespace std;

#define MAX 5
#define STR_LENGTH 40

void main()
{
    char *p_str[MAX];

    for (int i = 0; i < MAX; i++)
    {
        *(p_str+i) = new char(STR_LENGTH);
        cout << "Please enter a string:  ";
        cin >> *(p_str+i);
    }

    for (int i = 0; i < MAX; i++)
    {
        cout << *(p_str+i) << endl;
        delete (p_str+i);
    }

}

And that last line in there, I have that delete, but it breaks when it gets there, any ideas how to solve it please?

4

1 回答 1

8

new char(STR_LENGTH)不做你认为它做的事。它为单个 char 分配内存,初始化为STR_LENGTH. 正如所写,您有一个缓冲区溢出。让它new char[STR_LENGTH]

既然您正在分配一个数组,您应该使用delete [] (p_str+i);或者更简洁地释放它,delete [] p_str[i];

于 2013-09-06T14:21:26.653 回答