【发布时间】:2021-11-05 14:03:27
【问题描述】:
我目前正在练习指针算术,但在使用delete [] arr; 执行最后一行时,我无法弄清楚为什么这段代码会以“free(): invalid pointer”错误结束。
我意识到,在我的 Android 手机上使用 C4Droid 程序(使用编译器“G++ + Bionic”)时,相同的代码运行没有任何问题,但在我使用 GCC 的平板电脑上,它只是不起作用。我发现的唯一方法是确保 arr 数组当前指向第一个地址。它没有的那一刻似乎失败了。我不知道它是否应该在我的手机上也失败,或者它是否是我在平板电脑上使用的 IDE 中的配置问题(尝试使用代码块和 codelite)。你能帮忙吗?
我也很清楚,我正在为数组的前两个点初始化值,而在技术上可以选择比这更小的数组大小。这只是测试。
#include <string>
#include <iostream>
int main()
{
int *arr{};
size_t size{};
std::cout << "Please enter the size of the array you want to create: "; std::cin >> size;
arr = new int[size];
*(arr + 0) = 5;
*(arr + 1) = 10;
std::cout << "++arr: " << ++arr << " (pointer incrementation, we move by an int and arr is now arr + 1)" << std::endl;
delete [] arr;
return 0;
}
【问题讨论】:
-
“我不知道它是否应该在我的手机上也失败” - 这是未定义的行为。它可以为所欲为,包括崩溃、不崩溃、看似正常工作、格式化硬盘或making demons fly out of your nose。您只能使用
new分配的delete指针,仅此而已。 -
arr不是用new分配的arr,因为您增加了指针。 -
“运行没有任何问题”应该是“运行没有任何问题我可以检测到”。有问题,但是Android下的症状很微妙。
标签: c++ arrays pointers dynamic-memory-allocation delete-operator