malloc()
allocates a memory chunk which is virtually contiguous inside the process memory space. malloc()
takes a size as a parameter in bytes and returns pointer to that allocated memory space but what if the requirement is to allocate memory which is 4k aligned?
Asked
Active
Viewed 2,876 times
1

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

Kaushal Billore
- 41
- 1
- 6
-
You probably mean `aligned` not `aliened` – Basile Starynkevitch Jul 03 '13 at 05:53
-
Maybe you should [read this question](http://stackoverflow.com/questions/227897/solve-the-memory-alignment-in-c-interview-question-that-stumped-me/227900#227900) which is about a very similar problem, although for general (not Linux specific) domain. – Jubatian Jul 07 '13 at 12:10
3 Answers
3
That would almost certainly be achieved using something like posix_memalign.

Gian
- 13,735
- 44
- 51
-
If you can provide a simple example shows how to use it to get 4k aligned, that will be very helpful. – Jason Liu Sep 19 '19 at 19:58
1
Since 4Kbytes is often the size of a page (see sysconf(3) with _SC_PAGESIZE
or the old getpagesize(2) syscall) you could use mmap(2) syscall (which is used by malloc
and posix_memalign
) to get 4Kaligned memory.

Basile Starynkevitch
- 223,805
- 18
- 296
- 547
-
Note that if you use `mmap()` directly you may find yourself with less memory available. In the most pessimal case, allocating 4 KiB blocks from `mmap()` gives a maximum of 256 MiB total memory allocated, since there is a 2^16 limit on number of `mmap()` regions. – Dietrich Epp Jul 03 '13 at 06:28
-
1I don't think there is a 2^16 limit on the number of `mmap`-ed segments. My [manydl.c](http://starynkevitch.net/Basile/manydl.c) example is able to make many hundred thousands `dlopen` (and each of them uses more than one `mmap`-ed segment). – Basile Starynkevitch Jul 03 '13 at 07:40
0
you can not allocate physically contiguous memory in user space. Because in User space kernel always allocates memory from highmem zone. But if you are writing a kernel module or a system space code then you can use _get_page() or _get_pages().

Amit Bhaira
- 1,687
- 6
- 18
- 31
-
The function posix_memalign() allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated memory will be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size is 0, then the value placed in *memptr is either NULL, or a unique pointer value that can later be successfully passed to free(3). – LtWorf Jul 16 '14 at 16:57