[英]Why am I getting warning 'C6386' Buffer overrun while writing to 'ptr'?
在此示例中,变量“大小”为 10。 如果我用硬编码 10 代替“int(size)”,超限警告就会消失。 为什么会发生这种情况的任何建议/推理? 我想为我的指针分配 80 个字节,每个分配的值都是给定时间跨度的一个时间步长。
谢谢!
int main() {
const double h = 0.1;
const double tspan[2] = { 0.0, 1.0 };
const double size =round(tspan[1] / h);
double *ptr = (double*)malloc(int(size) * sizeof(double));
if (!ptr) {
cout << "Memory Allocation Failed";
exit(1);
}
double j = 0;
for (int i = 0; i < size; i++) {
ptr[i] = j;
//cout << j << '\n';
j++;
}
cout << '\n';
for (int i = 0; i < size; i++) {
cout << *(ptr + i) << endl;
//cout << i << '\n';
}
free(ptr);
return 0;
}
我试过取消引用指针并确保它不是 NULL。 我也打印了结果。 结果是一个计数 0-9 的指针。 `
double size
可以是10.1
,条件i < 10.1
不终止循环如果i
是 10,分配的缓冲区大小是int(10.1)
,即 10, ptr[10]
导致缓冲区溢出。
作为 273K 回答的补充,您 csn 通过将size
作为std::size_t
变量来解决这个问题。
让我们对该除法的结果进行 floor 并转换为int
。
int main() {
const double h = 0.1;
const double tspan[2] = { 0.0, 1.0 };
const int size = static_cast<int>(std::floor(tspan[1] / h));
double *ptr = (double*)malloc(size * sizeof(double));
if (!ptr) {
cout << "Memory Allocation Failed";
exit(1);
}
double j = 0;
for (int i = 0; i < size; i++) {
ptr[i] = j;
//cout << j << '\n';
j++;
}
cout << '\n';
for (int i = 0; i < size; i++) {
cout << *(ptr + i) << endl;
//cout << i << '\n';
}
free(ptr);
return 0;
}
更好的是,让我们使用 new 和 delete 而不是 malloc 和 free。
int main() {
const double h = 0.1;
const double tspan[2] = { 0.0, 1.0 };
const int size = static_cast<int>(std::floor(tspan[1] / h));
double *ptr = new double[size];
if (!ptr) {
std::cout << "Memory Allocation Failed";
exit(1);
}
double j = 0;
for (int i = 0; i < size; i++) {
ptr[i] = j;
//std::cout << j << '\n';
j++;
}
std::cout << '\n';
for (int i = 0; i < size; i++) {
std::cout << *(ptr + i) << std::endl;
//cout << i << '\n';
}
delete[] ptr;
return 0;
}
更好的是,使用std::vector
。
int main() {
const double h = 0.1;
const double tspan[2] = { 0.0, 1.0 };
const int size = static_cast<int>(std::floor(tspan[1] / h));
std::vector<double> vec(size);
double j = 0;
for (auto &x : vec) {
x = j;
//std::cout << j << '\n';
j++;
}
std::cout << '\n';
for (auto x : vec) {
std::cout << x << std::endl;
//std::cout << i << '\n';
}
return 0;
}
round()
四舍五入到最接近的整数。 如果有的话,你应该使用ceil()
来四舍五入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.