Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can "pragma pack 1" be helpful to avoid heap fragmentation?

In my program I see some resident size increase. I suppose it is because of heap fragmentation. So I am planning to use #pragma pack 1. Will it reduce the heap fragmentation?

Will it be having some other overheads?

Shall I go for it or not?

like image 203
piyush Avatar asked May 06 '14 07:05

piyush


People also ask

How can we avoid heap fragmentation?

Use a static array of structs, each struct has: A solid chunk of memory that can hold N images -- the chunking will help control fragmentation -- try an initial N of 5 or so. A parallel array of bools indicating whether the corresponding image is in use.

What does pragma Pack 1 do?

When you use #pragma pack(1) , this changes the default structure packing to byte packing, removing all padding bytes normally inserted to preserve alignment.

Why do you use #pragma pack 1 explain it with an example?

The #pragma pack directive cannot increase the alignment of a member, but rather can decrease the alignment. For example, for a member with data type of short , a #pragma pack(1) directive would cause that member to be packed in the structure on a 1-byte boundary, while a #pragma pack(4) directive would have no effect.

What is pragma push and pop?

#pragma pack(push[, n ]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry).


2 Answers

There is a well proved technique called Memory pools. It is designed especially to reduce memory fragmentation and help with memory leaks. And it should be used in case where memory fragmentation became the bottleneck of the program functionality.

'pragma pack 1' isn't helpful to avoid heap fragmentation.

'pragma pack 1' is used to remove the padding bytes from structures to help with transmission of binary structures between programs.

like image 186
alexander Avatar answered Sep 30 '22 02:09

alexander


It's simply how the operating system works. When you free some memory you've allocated, it's not unmapped from the process memory map. This is kind of an optimization from the OS in case the process needs to allocate more memory again, because then the OS doesn't have to add a new mapping to the process memory map.

like image 21
Some programmer dude Avatar answered Sep 30 '22 04:09

Some programmer dude