在C 中动态分配的内存的问题
Issue With Freeing Dynamically Allocated Memory In 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...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
取消指针作为零尺寸的请求返回的效果不确定。
相关文章:
- C++ 中 std::vector 的内存问题
- 实现快速排序的内存问题
- 此add_node函数会导致内存问题吗?
- C++:为什么这段代码给我内存问题/未定义的行为?
- 我不明白附加字符串的内存问题
- 是否有可能存在不会崩溃程序的内存问题
- 在发布版本中删除类指针会导致内存问题
- Android OpenCV 应用程序的内存问题
- 线程的内存问题(微小线程,C++)
- 递归结构的向量有内存问题
- C++合并排序内存问题
- 将智能指针发送到Protobaf.内存问题
- 潜在的动态内存问题
- JNI 中的内存问题
- C++Lambda函数关闭-内存问题
- 解决由全局静态变量引起的内存问题
- 类堆栈内存问题(致命错误)
- QNetworkAccessManager内存问题
- 读取进程内存问题未更新
- 类指针内存问题