C++中size_t循环的坑
Xhofe Lv3

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include"utils.h"
#include<iostream>
using namespace std;

void calMinDis()
{
bool **_map = NULL;
int **_min_dis;
int _height = 100;
int _width = 200;

_map = new bool*[_height];
for (size_t i = 0; i < _height; i++)
{
_map[i] = new bool[_width];
}

printf("cal min dis.\n");
if (_map == NULL)
{
printf("map haven't init.\n");
return;
}

_min_dis = new int *[_height];
for (size_t i = 0; i < _height; i++)
{
_min_dis[i] = new int[_width];
}
int MAX_INT = 0xffffffff >> 1;
for (size_t i = 0; i < _height; i++)
{
for (size_t j = 0; j < _width; j++)
{
if (_map[i][j])
{
_min_dis[i][j] = MAX_INT;
}
else
{
_min_dis[i][j] = 0;
}
}
}
for (size_t i = 0; i < _height; i++)
{
for (size_t j = 0; j < _width; j++)
{
if (!_map[i][j])
{
continue;
}
if (i > 0 && _min_dis[i - 1][j] < _min_dis[i][j])
{
_min_dis[i][j] = _min_dis[i - 1][j] + 1;
}
if (j > 0 && _min_dis[i][j - 1] < _min_dis[i][j])
{
_min_dis[i][j] = _min_dis[i][j - 1] + 1;
}
}
}
printf("1\n");
for (size_t i = _height - 1; i >= 0; i--)
{
for (size_t j = _width - 1; j >= 0; j--)
{
printf("(%d,%d)\n",i,j);
if (!_map[i][j])
{
continue;
}
if (i + 1 < _height && _min_dis[i + 1][j] < _min_dis[i][j])
{
_min_dis[i][j] = _min_dis[i + 1][j] + 1;
}
if (j + 1 < _width && _min_dis[i][j + 1] < _min_dis[i][j])
{
_min_dis[i][j] = _min_dis[i][j + 1] + 1;
}
}
}
printf("finished cal min dis.\n");
}

int main(int argc, char const *argv[])
{
calMinDis();
return 0;
}

这段代码看起来没什么问题,实则隐藏了很大的坑,因为for (size_t i = _height - 1; i >= 0; i--)这个循环中使用了size_t,加上输出之后会发现,循环停不下来,直至出现segmentation fault;
这是因为size_t是一种非负类型,它永远都不可能会小于0,所以循环停不下来。把size_t改成int就没问题了。

  • 本文标题:C++中size_t循环的坑
  • 本文作者:Xhofe
  • 创建时间:2021-04-13 14:08:00
  • 本文链接:https://nn.ci/posts/cpp-size_t-compare.html
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论