Warum führt der folgende Code zum Fehler Segmentation? (Ich versuche, zwei Matrizen der gleichen Größe zu erstellen, eine mit statischen und das andere mit der dynamischen Zuordnung)Speicherzuordnung für eine Matrix in C
#include <stdio.h>
#include <stdlib.h>
//Segmentation fault!
int main(){
#define X 5000
#define Y 6000
int i;
int a[X][Y];
int** b = (int**) malloc(sizeof(int*) * X);
for(i=0; i<X; i++){
b[i] = malloc (sizeof(int) * Y);
}
}
Seltsam genug, wenn ich eine der Matrix Definitionen Kommentar aus, wird der Code in Ordnung. Wie folgt aus:
#include <stdio.h>
#include <stdlib.h>
//No Segmentation fault!
int main(){
#define X 5000
#define Y 6000
int i;
//int a[X][Y];
int** b = (int**) malloc(sizeof(int*) * X);
for(i=0; i<X; i++){
b[i] = malloc (sizeof(int) * Y);
}
}
oder
#include <stdio.h>
#include <stdlib.h>
//No Segmentation fault!
int main(){
#define X 5000
#define Y 6000
int i;
int a[X][Y];
//int** b = (int**) malloc(sizeof(int*) * X);
//for(i=0; i<X; i++){
// b[i] = malloc (sizeof(int) * Y);
//}
}
Ich bin mit gcc unter Linux auf einer 32-Bit-Maschine.
Edit: zu überprüfen, ob malloc() erfolgreich:
#include <stdio.h>
#include <stdlib.h>
//No Segmentation fault!
int main(){
#define X 5000
#define Y 6000
int i;
int a[X][Y];
int* tmp;
int** b = (int**) malloc(sizeof(int*) * X);
if(!b){
printf("Error on first malloc.\n");
}
else{
for(i=0; i<X; i++){
tmp = malloc (sizeof(int) * Y);
if(tmp)
b[i] = tmp;
else{
printf("Error on second malloc, i=%d.\n", i);
return;
}
}
}
}
Nichts wird gedruckt, wenn ich es laufen (erwarten natürlich für "Segmentation fault")
Versuchen Sie 'fprintf' zu' stderr'. 'printf' druckt auf' stdout', was gepuffert ist. Wenn das Programm abstürzt, werden Sie wahrscheinlich die Ausgabe verlieren. –
Kannst du auch ausdrucken und sehen, wie weit es in der Schleife geht, bevor es scheitert? –