受this topic的启发,我决定编写一个简单的程序。
逻辑并不复杂,我有一个工作程序75%的时间..被询问的数量被定义为#define BUFSIZE x
,其中x
可以是一个任意的int。
问题出现在((BUFSIZE+1) % sizeof(int)) == 0
。程序行为不当25%的时间
因此,例如,如果BUFSIZE=10
,我的程序行为正确,当BUFSIZE=11
我得到奇怪的行为。
这里是源代码:
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 7
int max(int *buf);
int main()
{
int bufsize = BUFSIZE, *buf = malloc(sizeof(int[bufsize]));
// read values
int *ptr = buf;
while(--bufsize + 1)
{
printf("Input %d: ", BUFSIZE - bufsize);
scanf("%d", ptr);
++ptr;
}
// reset pointer and determine max
ptr = buf;
printf("\nMax: %d\n", max(ptr));
// cleanup
free(buf);
ptr = NULL;
buf = NULL;
exit(EXIT_SUCCESS);
}
int max(int *buf)
{
int max = 0;
while(*buf)
{
printf("%d\n", *buf);
if(*buf > max) max = *buf;
++buf;
}
return max;
}
而对于BUFSIZE = 2(正确的)和BUFSIZE = 3(不正确的)一些示例输出。
suze:/home/born05/htdocs/experiments/c# gcc input.c && ./a.out
Input 1: 12
Input 2: 23
12
23
Max: 23
suze:/home/born05/htdocs/experiments/c# gcc input.c && ./a.out
Input 1: 12
Input 2: 23
Input 3: 34
12
23
34
135153
Max: 135153
我有感觉这是非常合乎逻辑的事情,但我不能把我的手指放在这种不正当行为的确切原因。有人能指出我的这个(也许是明显的)缺陷吗?
呃?你在'buf [3]'和'buf [4]'分别使用了一个标记值,但你的大小分别是2和3。 – falstro 2010-07-26 12:00:05