引用 | 编辑
ebolaman
2011-09-16 13:44 |
楼主
▼ |
||
x0
最近练一个类似 Online Judge 的题目,结果一直错误,请教如何解决题目 : https://gpe2.acm-icpc.tw//showproblemtab.php?probid=2008-01&cid=2 我写的 C 程式码 : #include<stdio.h> #include<stdlib.h> /*========== Prototype ==========*/ void renew_realloc_pos(int*, int, int*); bool renew_plus_pos(int*, int*, int*); /*_______________________________*/ int main() { int maxNum = 0, lenNum = 0; int val_case = 1; int* pos; while (scanf("%d %d", &maxNum, &lenNum) == 2) { /*----- Initialize -----*/ pos = new int; pos = 1; renew_realloc_pos(pos, 1, &maxNum); /*----- Output -----*/ int rep = 1, i = 0; printf("case .. 访客只能看到部份内容,免费 加入会员 x0
|
引用 | 编辑
Freelife
2011-09-30 14:40 |
1楼
▲ ▼ |
输入 "0 0",会当掉是正常的,
pos = new int[lenNum]; 当lenNum = 0时, 不就怪怪的...... 最小值也要1.... x1 |
引用 | 编辑
Freelife
2011-10-03 10:02 |
3楼
▲ ▼ |
这是因为呢.....
你实际存取的记忆体, 超过你动态配置的大小...... 例如第二个输入范例:6 3 你配置3个int的阵列空间 pos = new int[3]; 但是,在renew_realloc_pos(...)函式里面, 你实际存取的pos[]阵列,却会取到第6个阵列值, 这样就有记忆体违规存取的问题..... 如果直接宣告成"pos[10] ", 当你存取超过阵列范围的大小时, 应该也是有问题的 x1 |
引用 | 编辑
ebolaman
2011-10-03 21:29 |
4楼
▲ |
下面是引用 Freelife 于 2011-10-03 10:02 发表的 : 所以,pos 会存取到不该是分配记忆体位置的 区域 却是在 delete [] pos; 才会发生问题呀 之前的焦点一直注意在 new int[]; 与 delete [] pos; 两个地方 原来我又犯了 多1或少1 的错误了 x0 |