mein Programm schlägt immer in der 4. Realloc und ich verstehe nicht, warum es die 3 zuerst gut und dann scheitert es. Ich benutze Triple Pointer und ich habe versucht zu debuggen und alles funktioniert gut bis zum 4. Realloc, wenn es sagt, dass es außerhalb des Bereichs und Segmentierung Fehler ist.Fehler in mehreren Realloc C Pointer
#include <stdio.h>
#include <stdlib.h>
void rellenar(int ***movimiento, int mov, int discos) {
int j, pos, mov2, ***movimiento2;
mov2 = mov + 1;
movimiento = realloc(movimiento, mov2 * sizeof (int **));
movimiento[mov] = malloc(3 * sizeof (int *)); //3 de torres
for (j = 0; j < 3; ++j) {
movimiento[mov][j] = malloc(discos);
}
printf("%d\n", mov);
for (pos = 0; pos < discos; pos++) {
movimiento[mov][0][pos] = 1;
movimiento[mov][1][pos] = 1;
movimiento[mov][2][pos] = 1;
printf("%d", movimiento[mov-1][0][pos]);
printf("%d", movimiento[mov-1][1][pos]);
printf("%d\n", movimiento[mov-1][2][pos]);
}
}
int main(int argc, char** argv) {
int ***movimiento, i, j, movs = 1, discos = 4, pos, mov;
movimiento = malloc(movs * sizeof (int **));
for (i = 0; i < movs; ++i) {
movimiento[i] = malloc(3 * sizeof (int *)); //3 de torres
for (j = 0; j < 3; ++j) //3 de torres
{
movimiento[i][j] = malloc(discos);
}
}
for (pos = 0; pos < discos; pos++) {
movimiento[0][0][pos] = discos - pos;
movimiento[0][1][pos] = 0;
movimiento[0][2][pos] = 2;
}
for (pos = 0; pos < discos; pos++) {
printf("%d", movimiento[0][0][pos]);
printf("%d", movimiento[0][1][pos]);
printf("%d\n", movimiento[0][2][pos]);
}
for (mov = 1; mov < 6; mov++) {
rellenar(movimiento, mov, discos);
}
}
Was ist los?
'movimiento [i] [j] = malloc (Diskotheken);' -> 'movimiento [i] [j ] = malloc (discos * sizeof (int)); '. Gleiches gilt für andere Orte, an denen Sie ähnliche "Mallocs" machen. – kaylum
Noch besserer Hinweis: Wenn Sie auf einer unterstützten Plattform (z. B. Linux) arbeiten, führen Sie [valgrind] (http://valgrind.org) aus, damit Sie Speicherbeschädigungen wie diese leichter finden. Es wird Ihnen viel Zeit sparen. – kaylum
Wie kaylum sagte, hast du vergessen, 'discos' mit' sizeof (int) 'zu multiplizieren, um die richtige Menge an Speicher für' movemiento [i] [j] 'zu reservieren. Infolgedessen schreiben Sie über den zugewiesenen Speicher hinaus und beschädigen Ihren Speicherstatus. Alle Wetten sind aus, sobald das passiert. –