gpt4 book ai didi

c++ - 为什么此代码在运行大小 [6, 10, 14, ...] 时中止

转载 作者:行者123 更新时间:2023-11-30 02:59:45 25 4
gpt4 key购买 nike

这是我为实现 Sieve of Eratosthenes 编写的一些代码:

#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
#include <cstdlib>

int allPrimes (unsigned long n) {
std::vector<int> track (n, 0);
int index = 2;
int m = sqrt(n);
while(index < n) {
if (track[index] == 0) {
std::cout << index << std::endl;
int mul = 1;
while ((index <= m) && (n >= (index * ++mul))) {
track[index * mul] = 1;
}
}
index++;
}
}

int main() {
int num;
std::cin >> num;
allPrimes(num);
}

奇怪的是,每当 num 在系列 6、10、14、18、22 中时,...代码在释放内存时会中止 folloiwng 堆栈(对于其他 n 运行正常):

raise () from /lib64/libc.so.6
abort () from /lib64/libc.so.6
__libc_message () from /lib64/libc.so.6
malloc_printerr () from /lib64/libc.so.6
_int_free () from /lib64/libc.so.6
__gnu_cxx::new_allocator<int>::deallocate
std::_Vector_base<int, std::allocator<int> >::_M_deallocate
std::_Vector_base<int, std::allocator<int> >::~_Vector_base
std::vector<int, std::allocator<int> >::~vector
allPrimes (n=6) at allprimes.cpp:20
main () at allprimes.cpp:26

但我没有看到错误,也没有看到这些以 4 为间隔的数字背后的逻辑。这里的错误是什么?

最佳答案

这里:

while(index <= n) {
if (track[index] == 0) {

您允许index跑到n , 这是越界的。你需要n-1 , 或 while (index < n) .代码中还有其他此类索引错误,所有这些都会导致未定义的行为。

关于c++ - 为什么此代码在运行大小 [6, 10, 14, ...] 时中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com