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

Issue With Freeing Dynamically Allocated Memory In C++

本文关键字:内存 问题 动态分配      更新时间:2023-10-16

我的程序可以释放内存并结束它崩溃。从功能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...nn";
    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 << "nnEnter 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 << "nnProgram end.";
}

您从未分配任何内存。

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

这是

等效的
int *movieData_ptr = new int[0];

您分配了0 int的大小。这是未定义的行为。如果没有分割故障,您将无法对该指针做任何有用的事情。您需要预先分配一定的数量,并确保每次计划添加数据时都不会溢出或动态分配。

由于这是C ,因此最好不要使用原始指针,而是使用向量或其他东西。

对不起:

从5.3.4/7

当直接新 - 亮相器中表达式的值为零时,分配函数被调用以分配没有元素的数组。

来自3.7.3.1/2

取消指针作为零尺寸的请求返回的效果不确定。