Possible to use munmap without knowing the length?

Is it possible to use “munmap” without knowing the length of data which was originally mapped?

I’m porting code and have had to change "malloc"s and "free"s to “mmap” and “munmap” to ensure that the cache isn’t used. (Otherwise I get problems with a DMA transfer). My problem is that the pointer to the memory is easily available but the length isn’t so readily available because it wasn’t required for the “free” command.

Is there a default value which i can give for the length in the “munmap” command which ensures that all the mapped memory associated with this pointer is unmapped?

Thanks in advance!

if u do not provide correct size, some system pages may remain allocated …

There is a simple solution. Replace malloc/free with something like my_malloc and my_free.

void * my_malloc( size_t size )
int *pt;

pt = mmap ( …, size + sizeof ( size ) );

*pt = size;

return &pt[1];


my_free(void *pointer)
size_t size;
int *pt = pointer;

size = *pt;

munmap ( pt, size );


The idea is to store the size in the allocated memory area but return a pointer that is just after the memory area that holds the size. I prefer to put it at the beginning instead of at the end because it’s less likely to be overwritten ;-)


 return &pt[1];

if that is ok with the memory alignment requirements of the DMA …

Thanks Mario! That’s exactly what i needed. :slight_smile:

It’s a good point Mezek but fortunately that shouldn’t cause a problem with our system.

I think there could be a small mistake in your suggestion - am i right in thinking that the line …

“munmap ( pt, size );”

… should be …

“munmap ( pt, size + sizeof ( size ) );” ? (Or have i missed something?)

Yes sorry

If Dma would be a problem. either make the header big enough to create a dummy space that keeps the aligment inline with the harware requirement or write the size at the end. But as I said the end is bad…

pt is a “int *”, so &pt[1] is safe.

Yes and no xtang. Some DMA devices require page to be align on 4k boundary. I have seen one that needed to be align on 32 bytes.