Free

Free is a function to deallocate memory obtained from malloc and other functions in C. Do not use this tag to refer to free software

Malloc

The malloc function performs dynamic memory allocation in C and is part of the standard library

Constructor destructor standard

Example

"This is better than malloc free at least because new will automatically call a constructor and delete will call a destructor"

from question  

Is placement new required when using allocated memory with fundamental data types? std::complex?

"And also remember to call the destructor yourself before calling free since free doesn t call destructors either;malloc allocates a memory block but does not actually construct an object there so it will contain garbage"

from question  

Default size of std::queue when creating it by malloc

"Free is a c standard library function and does not call the destructor of an object;and malloc does not call the constructor."

from question  

Free struct containing vector

"Applying new delete to a class type t will call the constructor and destructor respectively of t malloc free do not call the constructor and destructor of t;malloc will return null in case of memory exhaustion new will throw an exception"

from question  

How does the delete in C++ know how many memory locations to delete

Extensible prone

Example

"This avoids malloc free but is less extensible and more prone to buffer overflow issues so i rarely ever use bytedata"

from question  

How to convert NSData to byte array in iPhone?

"This avoids malloc free but is less extensible and more prone to buffer overflow issues so i rarely ever use this"

from question  

Iphone NSMutableData bytes index

System calls d

Example

"Because system calls are costly your standard library will try to avoid system calls and prefer marking free -d memory zones as reusable in future malloc -s"

from question  

How to reallocate memory anyhow, even if realloc() failed in c++

"You can think of the memory free but not released back to the operating system as your own personal cache of memory;this is all assuming of course that malloc uses sbrk at all"

from question  

Why doesn't a call to free() reduce the size of the heap?

Memory size null

Example

"Here is a solution which encapsulates the call to malloc allocates a bigger buffer for alignment purpose and stores the original allocated address just before the aligned buffer for a later call to free"

from question  

How to allocate and free aligned memory in C

"How does free know how much memory to be free d which was earlier allocated by malloc or calloc"

from question  

How does free know the size of memory to be freed?

"One interesting experiment you can try is to try and malloc more memory after you free d that pointer"

from question  

C - Accessing data AFTER memory has been free()ed?

"Where i work malloc free is slower and more inefficient than new delete for two reasons free does not know the size of the object whereas delete often has this size at compile-time"

from question  

Why are new()/delete() slower than malloc()/free()?

"Malloc finds 10 more free bytes and marks them as used"

from question  

What happens when you call malloc on an existing variable?

"Now if you free some values on the heap and allocate more with malloc you may be given back some of that dirtied memory that you scribbed on earlier"

from question  

Uninitialised values of heap and stack space

"Thus if your memory size is not large some malloc may fail even if the total free memory is bigger that requested"

from question  

Result of using millions of malloc()s and free()s in your C code?

"Then you are correct in thinking that without a destructor the memory allocated by malloc will not be free;if you follow the rules above then you need to use free not to deallocate it"

from question  

Doubts with destructor

"When all malloc entries in a virtual page are free that virtual page is then released back to the os this also implies that free does not always release memory back to the os since the virtual page may still have other malloc entries in it;if there is not enough space within a given virtual page to support another malloc of a specified size another virtual page is requested from the os"

from question  

Dynamic memory allocation and memory block metadata

"As far as malloc realloc and free are concerned memory is just a flat array of bytes;if you store pointers in memory that s you choice but malloc doesn t care"

from question  

How deep does realloc free when it copies my data in memory?

"Although some compiler allocate memory for new using malloc free doesn t call destructors;so if you mix new with free you ll get memory leaks and a lot of hard to deal with problems"

from question  

Should a warning or perhaps even an assertion failure be produced if delete is used to free memory obtained using malloc()?

"Garbage-collection may be slower than malloc and free for programs that allocate at once all the memory garbage-collection need and work with that"

from question  

Is Java really slow?

"If you are working on an embedded system that has limited memory good chances are that the malloc returned a null because you were attempting to request more memory than the malloc had free in one contiguous block"

from question  

What to do if malloc returns NULL?

"Such an operation in reality would lead to a memory leak as the memory address which was stored in a initially is not free and is no more pointed by anyone;let the first malloc in main fetch the address 0x1234abcd"

from question  

* (no title is found for this review)

"That allows free to know the size of your memory even though free does not get the size parameter malloc got;the same data also allows malloc to know how much space is available and where"

from question  

Is it valid returning locally allocated memory - not local variables

"So with that malloc function no your free does not free the memory;first of all you re losing the address of the memory so every time you call this malloc you re actually pushing the process break a little further and never reuse freed memory locations"

from question  

Redefining free memory function in C

"Here s why checking for null in free is more than just a nice idea;when you use malloc you don t have to remember how much memory you asked for the heap manager does that for you"

from question  

Is there any extra overhead in free that checks for a null pointer?

"Suppose char p malloc n assigns more than n say n bytes of memory are allocated and free p is used to free the memory allocated to p"

from question  

What happens when tried to free memory allocated by heap manager, which allocates more than asked for?

"Use malloc or calloc to allocate memory realloc to allocate or extend a buffer that s been allocated with malloc calloc or realloc and free to deallocate memory that was allocated with malloc calloc or realloc;malloc does not initialize the dynamically-allocated memory"

from question  

Need help translating java program to C

"And your only initializing first variable of struct but while you are trying to free the memory you are unallocating memory which is not yet allocated astruct 1 and so on till 100;when you use a malloc a malloc actually allocates a bit more memory than you you specified"

from question  

How to free dynamic 2d array that's in a struct?

"This makes it safe to free them all since free null is valid and does nothing;the memory returned by malloc is not initialized"

from question  

Trying to understand behavior when freeing allocated memory

"In the freememory you are trying to free memory not allocated with appropriate function malloc calloc or realloc;malloc used once to allocate memory for struct _employee but pointer stored in array the parameter of freememory are obviously not are pointers to _employee"

from question  

Bus error when allocating data of structs to an array and then Writing to a .txt file

Likely so-called metadata

Example

"The most likely explanation is that there s a memory bug in your program writing to free memory buffer overrun etc;an outright bug in malloc is far less likely"

from question  

Bug in malloc or mine?

"Most likely malloc allocates more memory and puts so-called guard values that happen to contain null bytes or it puts some metadata to be used by free later and this metadata happens to contain a null byte right at that position"

from question  

String doesn't end at NULL but still behaves normally, why?

Not track in

Example

"Finally like i stated in a comment to another answer the object will often have a hidden header that stores the size of the object so that a subsequent free can know how large a block is being returned;while your code will keep track of the total amount of memory request via malloc it isn t really keeping track of the total amount of memory used by the objects that are returned"

from question  

Wrapper around malloc will it work?

"Malloc keeps track of the memory that is free or not;in general malloc cannot return this arbitrary region of the heap to the os because the heap is a single contiguous region from the os point of view"

from question  

Mips memory management

"The successive free call therefore tries to free messageptr not the memory allocated by malloc;not only this the malloc ated memory will be lost since you have lost all reference the pointer to it"

from question  

Pointer being freed was not allocated in C

Delete different new

Example

"Yes it is undefined to free an object that you allocated with new primarily because free does not invoke class destructors;similarly for delete ing something you created with malloc to do so would be to mix two different allocation construction idioms and although you can make it work it would be spectacularly difficult to do so robustly"

from question  

New/delete/free store and malloc/free/heap combinations

"If your .so are statically linked to c++ runtimes - you should free objects in the same module where they were allocated since new delete is something more than malloc free and need some extra info to work properly"

from question  

Separate Heap on Linux?

"In this context free store is different and incompatible with heap because the new delete free store library is simpler and quicker than the malloc free realloc calloc heap library and thus provides huge memory usage gains to the c++ embedded programmer in a context where you have only 512 bytes of ram"

from question  

C++, Free-Store vs Heap

"His means using new gc instead of new gc_malloc instead of malloc and don t bother about free -ing or delete -ing memory objects;a couple of years ago i measured new gc_malloc versus malloc it was a bit slower perhaps 25µs for new gc_malloc versus 22µs for system malloc"

from question  

Malloc / new lock and multithreading

Others

Example

Free is the opposite of malloc;new calls malloc but does a bit more;as delete calls free but does something more

from question  

Why wouldn't gcc compile this trivial code that calls free() function?

Alloca is also non-standard unsafe and non-portable basically worse than using malloc and free in c++

from question  

Calling alloca() multiple times results in a contiguous part of stack?

1 okay so it is technically possible to allocate it as one big blob and then wire up the 20-element array to point into the desired offsets into the blob this convolutes free ing though and usually isn t necessary for most use-cases the performance gains would be negligible and you d still need to malloc a separate array of pointers that address into the 2d blob you typically only see 2d-blob allocation when data is massively 2d such as image data and access syntax is eschewed in favor of syntax because it s no less efficient than what the compiler would do and doesn t require more than one malloc free pair per blob of data

from question  

How to declare a char*[20][250]

Remember malloc is quite expensive action and free costs even much more than malloc

from question  

Sorting of an array using merge sort

Malloc is much easier to implement if there is no free

from question  

C: how does this code result in the freeing of malloc-ed space?

In addition to the previous answers the strncpy char pointer which seems unsafe for my opinion and the malloc which is safer but you need to remember to free it outside of the function and its inconsistent with the hierarchy of the program you can do the following

from question  

Error trying to change contents of string pointer in C

Additionally c++ s new and delete could actually request a larger amount of memory from malloc and use the extra for book keeping like storing the address of the destructor function and so the pointer you passed to free would not actually be one that was malloc ed;c++ wants to call a destructor on the object when you use delete but passing it to free doesn t allow this to happen

from question  

Why does calling free () on a pointer allocated with 'new' cause heap corruption?

Due to the a++ a pointer that malloc returned is no longer what malloc returned and thus free doesn t know what to do with a pointer that malloc returned

from question  

Why does free() need the starting pointer of a dynamic array?

Free accepts null pointers;malloc doesn t need a cast in c

from question  

Storing characters in char data type C language

On linux with glibc the memory is actually always returned to the os above a certain size glibc malloc uses mmap for big allocations controlled by mmap_threshold and in that case free calls munmap which frees automatically the reserved memory;below that threshold it uses brk and free does not return the memory in that case

from question  

UNIX vs Windows memory deallocation

Malloc will not free the allocated memory;you need to use free to free the allocated chunk

from question  

Will malloc automatically free the memory at the end of a function?

I don t know if getline will try to call free or not when it dynamically grows the buffer;if it does then the malloc one is very preferable.

from question  

Llinked list not printing correctly

Presumably the mac malloc aligns to bigger boundaries and so it s spotting the pointer you re passing to free can t be correct since it has the wrong alignment

from question  

Non-aligned pointer being freed on mac

Otherwise or if free ptr has already been called before undefined behavior occurs;since your str is a pointer obtained by adding a number to a pointer obtained from malloc it doesn t meet this requirement and undefined behaviour results

from question  

Free() complains about invalid pointer

The rest of the statement just says why it s invalid it s not from the stack it s not something you ve got from malloc and not been free recently;the recently is mentioned because valgrind keeps track of free memory for a limited number of frees so it can t say for sure that it wasn t free a million frees back - in this case it wasn t but if you see a message like that it may be that it has become invalid because it was free ages ago

from question  

Valgrind: Invalid read of size 1

The standard doesn t specify anything deeper than malloc and free which leaves c libraries free to implement t to work in t target environments

from question  

How to get the amount of used memory when an application is executed

The c++-way here is more readable in my opinion and new and delete are safer than malloc and free

from question  

C2440 error when using malloc c++

The reason malloc works is probably because or pulls in a declaration for malloc but not free;thus malloc is unmangled but free is mangled

from question  

LD_PRELOAD only working for malloc, not free

That means it is indeed allowed to call mprotect on malloc ed memory regions but free will not reset it as there is no way to know the old protection flags so i have to reset the flags before calling free;in fact this is exactly the problem i met when the program runs for a while it randomly crashes in malloc that is because malloc is writing it s housekeeping data into the previously allocated memory and that memory was set to prot_none by an earlier mprotect after i set the memory to writable before calling free the program never crash again

from question  

Do I need to reset protection before calling free

Once the pointed-to next node is free any malloc is no longer valid

from question  

Freeing pointers in structs pointing to other structs

Somebody say that this behavior can mask double-frees since free null doesn t produce errors but imho this is better than the alternative;one important detail you re not checking the return value of malloc which is quite bad

from question  

C -language dynamic memory

Edit don t forget that after malloc you use free and not delete to free the memory;i have to note that the usage of malloc is usually discouraged in favor of new in c++

from question  

C++ Create Object Array without default constructor

Well calling free is not mandatory as your os will reclaim the space allocated by malloc when you program ends but as long as your program runs you may be ocupying more space than you need to - and that s bad for your program for other programs for the os and the universe as a whole;malloc x creates space of size x bytes on the heap for you to play with

from question  

When to use malloc in function?

Back to Home
Data comes from Stack Exchange with CC-BY-SA-4.0