Speicherplatz und struct
-
hallo,
ich habe folgendes Problem und zwar wirft der folgende code beim Aufruf von free immer eine Ausnahme und ich weiss nicht warum.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Filme { char Name[20]; char Rate[20]; bool test; }; typedef struct Filme Film; int main() { Film *film; film = (Film*) calloc(1, sizeof(Film)); strcpy(film->Name, "Terminator"); strcpy(film->Rate, "10"); printf("%s %s", film->Name, film->Rate); film = (Film*) realloc(film, sizeof(Film)); strcpy(film[1].Name, "Sieben"); strcpy(film[1].Rate, "9"); printf("%s %s", film[1].Name, film[1].Rate); free(film); return 0; }
-
Weil du Speicherplatz für einen allozierst, aber in den zweiten schreibst, vielleicht?
-
ich schreibe in den ersten,
strcpy(film->Name, "Terminator"); strcpy(film->Rate, "10");erweitere dann den platz
film = (Film*) realloc(film, sizeof(Film));und schreibe noch in den 2.
strcpy(film[1].Name, "Sieben"); strcpy(film[1].Rate, "9");oder?
-
-> Man soll in C++ new/delete und überhaupt kein realloc verwenden

-> Wenn realloc dann richtig, der zweite Parameter gibt den neuen *insgesamten* Platz an, nicht die Differenz zur alten GrößeMfG SideWinder
-
realloc(film, sizeof(Film) * 2);
-
ah ok danke,
Ich hab realloc falsch verstanden, dachte der 2. parameter ist die größe um die der speicherplatz erweitert werden soll und nich die neue gesamt größe.
-
Aus den man-pages:
void *realloc(void *ptr, size_t size);
DESCRIPTION
[...]realloc() changes the size of the memory block pointed to
by ptr to size bytes. The contents will be unchanged to
the minimum of the old and new sizes; newly allocated mem
ory will be uninitialized. If ptr is NULL, the call is
equivalent to malloc(size); if size is equal to zero, the
call is equivalent to free(ptr). Unless ptr is NULL, it
must have been returned by an earlier call to malloc(),
calloc() or realloc().