在C ++中释放动态分配内存的问题

时间:2018-04-22 05:25:57

标签: c++

在我的程序释放内存并结束崩溃之前。崩溃似乎发生在从UserDataCollection函数转换回main的过程中。这只是我的第二个使用指针的程序,所以考虑到c ++的重点是使用指针,我仍然是新手。

以上是上述代码:

#include <iostream>

//Prototypes
void UserDataCollection(int * &movieData_ptr, int &numSurveyed); // Movie Statistics
void DisplayOutput(int *movieData_ptr, int numSurveyed); //Mean, Median, Mode (Display To Console)

//Global Constants

int main()
{
    //Variables
    int numSurveyed = 0;

    //Pointers
    int * movieData_ptr = nullptr;
    movieData_ptr = new int[numSurveyed];

    //"Program Start"
    std::cout << "Program start...\n\n";
    UserDataCollection(movieData_ptr, numSurveyed);
    DisplayOutput(movieData_ptr, numSurveyed);

    //Release Memory
    delete[] movieData_ptr;
    std::cout << "Memory Cleared.";

    return 0;
}

void UserDataCollection(int * &movieData_ptr, int &numSurveyed)
{
    //Get Number of Students Surveyed
    std::cout << "How many students were surveyed: ";
    std::cin >> numSurveyed;

    //Student Data Input Loop
    for (int i = 0; i < numSurveyed; i++)
    {
        //Get Student Data
        std::cout << "Enter How many movies student " << i + 1 << " has seen in ONE month: ";
        std::cin >> *(movieData_ptr + i);

        //Validation Check
        while (*(movieData_ptr + i) >= 337)
        {
            std::cout << "\nImpossible value!" << std::endl
                << "Hours in a month: 730. Average movie length: 130 minutes."
                << "Total Possible movies: 337";

            std::cout << "\n\nEnter How many movies student " << i + 1 << " has seen in ONE month: ";
            std::cin >> *(movieData_ptr + i);
        } //end while (Validation Check)
    } // end for (Data Input)
}

void DisplayOutput(int *movieData_ptr, int numSurveyed)
{
    //Display loop for pointer array
    for (int i = 0; i < numSurveyed; i++)
    {
        std::cout << *(movieData_ptr + i) << " ";
    }

    //End Message
    std::cout << "\n\nProgram end.";
}

1 个答案:

答案 0 :(得分:1)

你从未分配任何记忆。

int numSurveyed = 0;

//Pointers
int * movieData_ptr = nullptr;
movieData_ptr = new int[numSurveyed];

这相当于

int *movieData_ptr = new int[0];

您正在分配0个整数的大小。 这是未定义的行为。如果没有分段错误,您无法对该指针执行任何有用的操作。您需要预先分配一定数量,并确保不会溢出,或者每次计划添加数据时动态分配。

由于这是C ++,最好不要使用原始指针,而是使用vector或其他东西。

抱歉:

  

从5.3.4 / 7

     

当direct-new-declarator中的表达式的值为零时,调用分配函数来分配没有元素的数组。

     

从3.7.3.1/2

     

取消引用作为零大小请求返回的指针的效果未定义。