2014-09-19 126 views
0

这个小C程序每次都会崩溃。为什么这个程序崩溃?

它应该以3D格式的形式分配一块内存,该3D格栅由以3D友好模式放置在内存中的许多结构(单元)组成。结构将填充位置数据。

我不知道它为什么崩溃。它返回这个数字:c0000005。

#include <stdio.h> 
#include <malloc.h> 

typedef struct { 
int coords[3]; 
} cell; 

int main() { 

    int x=4, y=8, z=6; 

    int volume=x*y*z; 

    cell *arr=(cell*)calloc(volume,sizeof(cell)); 

    int u=0,v=0,w=0; 
    int index; 

    for (w=0; w<z; w++) { 
    for (v=0; v<y; v++) { 
    for (u=0; u<x; u++) { 

     //printf("%d %d %d\n", u, v, w); 

     index=u+v*y+w*y*z; 

     arr[index].coords[0]=u; 
     arr[index].coords[1]=v; 
     arr[index].coords[2]=w; 

     //getchar(); 

    }}} 

    printf("All done.\n"); 

    return 0; 
} 
+2

[不要施放malloc(和朋友)的结果](http://stackoverflow.com/q/605845) – Deduplicator 2014-09-19 19:18:13

+0

用所有的警告和调试信息('gcc -Wall -g')编译你的程序。然后**使用调试器**('gdb') – 2014-09-19 19:19:56

+1

您在计算索引时混淆了尺寸。 – Deduplicator 2014-09-19 19:20:10

回答

2

问题是index=u+v*y+w*y*z;

它应该是index=u+v*x+w*y*x;

所以@nos是对的。它会触发分段错误,因为6=z>x=4index会变得过大。

+0

是的,这是问题。谢谢。我可能可以避免它... – user2464424 2014-09-19 19:27:10