Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
How allocate memory which is page size aligned?

I need to allocate memory which should be page size aligned. I need to pass this memory to an ASM code which calculates xor of all data blocks. I need to do this with malloc().

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

There are functions for this that you're supposed to use.

If you can't, for whatever reason, then the way this is generally done is by adding the block size to the allocation size, then using integer-math trickery to round the pointer.

Something like this:

/* Note that alignment must be a power of two. */
void * allocate_aligned(size_t size, size_t alignment)
{
  const size_t mask = alignment - 1;
  const uintptr_t mem = (uintptr_t) malloc(size + alignment);
  return (void *) ((mem + mask) & ~mask);
}

This has not been very deeply tested but you get the idea.

Note that it becomes impossible to figure out the proper pointer to free() the memory later. To fix that, we would have to add some additional machinery:

typedef struct {
  void *aligned;
} AlignedMemory;

AlignedMemory * allocate_aligned2(size_t size, size_t alignment)
{
  const size_t mask = alignment - 1;
  AlignedMemory *am = malloc(sizeof *am + size + alignment);
  am->aligned = (void *) ((((uintptr_t) (am + 1)) + mask) & ~mask);
  return am;
}

This wraps the pointer trickery a bit, and gives you a pointer you can free(), but you need to dereference into the aligned pointer to get the properly aligned pointer.

over 4 years ago · Santiago Trujillo Denunciar

0

I don't think is possible only with malloc. You can use memalign():

char *data = memalign(PAGESIZE, alloc_size);

Where PAGESIZE is the size of a page and alloc_size is the size of the memory that will be allocated.

The size of the page can be found with sysconf(_SC_PAGESIZE).

over 4 years ago · Santiago Trujillo Denunciar

0

Use posix_memalign to obtain memory already aligned.

Note: valloc & memalign both are obsoleted.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda