realloc in Funktion auslagern
Hi!
Ich habe mal wieder eine kleine Frage. Ich möchte gerne realloc in eine Funktion auslagern:
Code:
void reallData(Data **data, int rows){
extern Count cnt;
data = (Data*) realloc(data, rows * sizeof(Data));
if(data == NULL){
fprintf(stderr, "out of memory\n");
// return 0;
}
data[0].id = 75;
int i;
for(i = cnt.value_rows; i < cnt.value_rows+rows; i++){
data[i].value = (double*) malloc(cnt.value_colums * sizeof(double));
data[i].value = i;
if(data[i].value == NULL){
fprintf(stderr, "out of memory\n");
// return 0;
}
}
}
Doch erhalte nur Fehlermeldungen.
Gelöst habe ich das Problem auch schon indem ich Data mit
in der Funktion initialisiert habe.
Doch eigentlich interessiert mich, warum es nicht funktioniert? Meiner Auffassung nach müsste es dem Compiler doch egal sein, ob noch ein Zeiger auf die Struktur zeigt oder nicht. Die Aufklärung würde mich wirklich interessieren.
Grüße dml!
Übung macht den Maeister!
Hi,
vielen Dank für Eure Unterstützung. Das Speicherleck wäre mir für eine längere Zeit, wenn überhaupt, gar nicht erst, aufgefallen. Ich habe noch eine Variante ausprobiert:
Code:
#include <stdio.h>
#include <stdlib.h>
void mymalloc(int *data,int rows){
data = malloc(rows*sizeof(*data));
}
void myrealloc(int *data,int rows){
data = realloc(data,rows*sizeof(*data));
}
void myrealloc2(int **data,int rows){
*data = realloc(*data,rows*sizeof(**data));
}
int main()
{
int *a;
printf("&a=%p, a=%p\n",&a,a);
a = malloc(sizeof(int));
// mymalloc(a, 1);
printf("&a=%p, a=%p\n",&a,a);
myrealloc(a, 6);
printf("&a=%p, a=%p\n",&a,a);
int *b;
b = malloc(sizeof(int));
myrealloc2(&b, 6);
int i;
for(i = 0; i < 6; i++){
a[i] = 1;
b[i] = 1;
}
for(i = 0; i < 6; i++){
printf("%d\n",b[i]);
}
printf("\n");
free(a);
free(b);
return 0;
}
Was zeigen würde, das ein Doppelpointer gar nicht erst benötigt wird.
Vielen Dank!