关于数组溢出部分的输出是怎样规定的?

#include "stdio.h"
void main()
{
int str[10]={34,21,43,22,54,76,32,12,38,96};
int i,j,x;
for(i=1;i<10;i++)
{
x=str[i];
j=i-1;
while(x<str[j])
{
str[j+1]=str[j];
j--;
if(j<0) //溢出了,为何这里的输出为1和7?
{
printf("%d",j);
printf("%d\n",str[j]);
}
}
str[j+1]=x;
}
for(i=0;i<10;i++)
printf("%d ",str[i]);
}

这是一个标准的插入排序,但是在第一次j--的时候数组str[-1]发生了溢出的现象,但程序运行仍然一切正常,而且在屏幕显示了str[-1]为7,我不大明白其中道理,对数组溢出的现象,计算机是依据什么去显示的呢?我应该怎样去修改这个程序呢?望各位多多指点……:)
(编译器为Visual C++ 6.0创天中文版)

[628 byte] By [FinlandRBT-芬兰兔子] at [2008-5-27]
# 1
这个,我想应该是垃圾数据吧。。
也就是内存上次使用后遗留下来的痕迹
# 2
It depends on the compile and/or OS. The str[-1] is at the memory next to str[0]. When you assign value to it, you overwrite somebody else. You can write program to see who you are writing to (actually, a while ago somebody asked same question and I have responsed to it), for example:

int i=0;
int array[] = {1};
int j = 2;

printf("&i=%d, &array[-1]=%d, &j=%d\n", &i, &array[-1], &j);
/* or */
array[-1] = 3;
printf("i = %d, j = %d\n", i, j);
do_do-do_do at 2007-10-26 > top of Msdn China Tech,C/C++,C语言...
# 3
首先我要说的是:所谓数组溢出就是所谓的越界访问。由于数组对应于内存中的一段地址空间,则空间前后还是内存,内存中存放有数据(可能是其他程序的,也可能是没有分配出去的,没分配出去不等于没有数据)。所以他还是按照你所定义的数组格式的这种方式访问,读出数据一点都不奇怪!
其实对于你上面的程序如果从溢出的角度完全不要去修改它,因为无效的读不会对于整个系统造成任何影响,经常强调的不能溢出是怕你的程序对于其他程序的数据进行了修改,这样可能造成被修改的程序不稳定或者发生莫名其妙的错误。
对于你的程序的修改是因为他会不停去寻找没有意义的内存空间,造成循环次数增多。修改如下:
# 4
#include "stdio.h"
void main()
{
int str[10]={34,21,43,22,54,76,32,12,38,96};
int i,j,x;
for(i=1;i<10;i++)
{
x=str[i];
j=i-1;
while((x<str[j])&&(j>=0))//修改的地方
{
str[j+1]=str[j];
j--;
if(j<0) //溢出了,为何这里的输出为1和7?
{
printf("%d",j);
printf("%d\n",str[j]);
}
}
str[j+1]=x;
}
for(i=0;i<10;i++)
printf("%d ",str[i]);
}
# 5
或者改成这样:
#include "stdio.h"
void main()
{
int str[10]={34,21,43,22,54,76,32,12,38,96};
int i,j,x;
for(i=1;i<10;i++)
{
x=str[i];
j=i-1;
while((x<str[j])&&(j>=0))//修改的地方
{
str[j+1]=str[j];
j--;
if(j<0) //溢出了,为何这里的输出为1和7?
break;//修改之处
}
str[j+1]=x;
}
for(i=0;i<10;i++)
printf("%d ",str[i]);
}
网速太慢,分两次发上!
# 6
C 语言根本不管什么越界不越界,假设 str 其实地址是 10000,它就只管读除地址 9999 的内容,一切越界问题都由程序员自己把握
alexxing-赤铸 at 2007-10-26 > top of Msdn China Tech,C/C++,C语言...
# 7
同意楼上。
# 8
哦,我才明白~~原来溢出的现象并没有我原来想象中的那么“恐怖”,呵呵,明白了,多谢各位的指点:)
FinlandRBT-芬兰兔子 at 2007-10-26 > top of Msdn China Tech,C/C++,C语言...
# 9
回答果然都很经典,都很有道理,很长见识。
baishi20-百事 at 2007-10-26 > top of Msdn China Tech,C/C++,C语言...
# 10
我怎么不能结帖?说什么“贴子回复次数大于跟给分次数 ”
FinlandRBT-芬兰兔子 at 2007-10-26 > top of Msdn China Tech,C/C++,C语言...