# terminate 调用后抛出 'thrust::system::system_error' 实例：what():  after cudaGetLastError: 遇到非法内存访问

- **ID:** `cuda/thrust-vector-alloc-failure`
- **领域:** cuda
- **类别:** runtime_error
- **错误码:** `cudaErrorIllegalAddress (77)`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Thrust 算法（如 thrust::sort、thrust::reduce）内部启动 CUDA 内核；当设备向量越界访问或主机指针被传递给设备端操作时，会发生非法内存访问，导致内核崩溃，Thrust 将其报告为 system_error。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CUDA 11.8 | active | — | — |
| CUDA 12.1 | active | — | — |
| Thrust 1.17.2 | active | — | — |
| Thrust 2.1.0 | active | — | — |

## 解决方案

1. ```
   Use cuda-memcheck or compute-sanitizer to pinpoint the exact illegal memory access location. Example: run the program with compute-sanitizer --tool memcheck ./my_program, then fix the out-of-bounds index.
   ```
2. ```
   Ensure all device vectors are properly sized and that host pointers are not accidentally passed to Thrust algorithms. Use thrust::device_vector for device data and thrust::host_vector for host data. Example: change thrust::sort(host_ptr, host_ptr+N) to thrust::sort(d_vec.begin(), d_vec.end()).
   ```

## 无效尝试

- **** — Resetting the device (cudaDeviceReset) does not fix the root cause; the illegal access will recur on the next Thrust call. (90% 失败率)
- **** — Increasing the device vector size arbitrarily may mask the out-of-bounds access but does not guarantee correctness; the real bug is in the algorithm logic. (75% 失败率)
