I write some code in C
#include <stdlib.h>
#include <stdio.h>
int width=3,height=6;
//if width>height, the programe will crash
void test(int ** input){
printf("test value:\n\n");
for(int i=0;i<width;i++){
for(int j=0;j<height;j++)
printf("%dx%d=%d\t",i,j,input[i][j]);
printf("\n");
}
}
int main()
{
int **p = (int**)malloc(sizeof(int*)*width); //for rows
for(int i = 0; i < height; i++)
{
*(p+i) = (int*)malloc(sizeof(int)*height);//for cols
}
for(int i =0;i<width;i++)
for(int j=0;j<height;j++)
p[i][j]=i*j;
test(p);
return 0;
}
run it:
gcc test.c && a.out
Nothing is wrong, everything is OK.
But, if i change width=7
at line 4. The code will crash:
Segmentation fault: 11
Why?
I run it in:
zenith@zenithdeMacBook-Air:/ramdisk$ uname -a
Darwin bogon 13.3.0 Darwin Kernel Version 13.3.0: Tue Jun 3 21:27:35 PDT 2014; root:xnu-2422.110.17~1/RELEASE_X86_64 x86_64
zenith@zenithdeMacBook-Air:/ramdisk$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix