brauch ich bei malloc immer ein free() in C?

2 Antworten

your process has a region of memory, from address x to address y, called the heap. All your malloc'd data lives in this area. malloc() keeps some data structure, let's say a list, of all the free chunks of space in the heap. When you call malloc, it looks through the list for a chunk that's big enough for you, returns a pointer to it, and records the fact that it's not free any more as well as how big it is. When you call free() with the same pointer, free() looks up how big that chunk is and adds it back into the list of free chunks(). If you call malloc() and it can't find any large enough chunk in the heap, it uses the brk() syscall to grow the heap, i.e. increase address y and cause all the addresses between the old y and the new y to be valid memory. brk() must be a syscall; there is no way to do the same thing entirely from userspace.

https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work

du nutz also irgendwo das free mit dem pointer um den bereich wieder freizugeben , wo du das machst ist egal , hauptsache du machst es .


Uffly007 
Fragesteller
 01.01.2023, 17:43

ok danke, noch ne frage:

sagen wir ich habe ne funktion mit einem struct als rückgabetyp, damit ich den code compilen kann muss ja irgendwo das struct definiert werden. Was aber wenn ich das nicht will gibts da irgendwie n Workaround?

Beispielsweise wenn man malloc benutzt muss man eig. stdlib einbinden, aber man kann ja auch die Definition oder so über den man befehl nachschauen und dann die definition nur für malloc einbinden. geht das mit nem struct auch irgendwie oder muss man den definieren ?

0
TechPech1984  01.01.2023, 17:50
@Uffly007

äh , wenn du eine functio hast die ein struct braucht für die rückgabe muss der natürlich definiert werden , sonst kann der compiler das ja gar nciht so anlegen . sollest du noch nciht wissen was du zurück gibst , dann musst du eine andere lösung finden die eine adresse zurück gibt und irgendwo wissen was für eine stuct das ist , das wäre dann z.b. einfach eine adresse als int oder so und dann ist es aber an dir daraus was schlaues zu machen . irgendwann wirst du die struct jedenfalls brauchen sonst kann nichts gelesen werden . und beim schreiben brauchste sie ja auch .

0

Jedes malloc braucht ein free.

Free muss dann aufgerufen werden wenn du das Array nicht mehr verwendest.

Ist im übrigen ein Stolperstein welcher für sehr viele Fehler in Software sorgt.