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

320
Vistas
In C, free half of the memory chunk, without freeing the other half

If I have allocated a memory chunk say

char *a =(char*)malloc(sizeof(char)*10);   

and I do

strcpy( "string of len 5",a);   

then is there a way to free the left over part of my memory chunk?
In other scenario if I do

strcpy("string of len5", (a+5));

then first half will be empty. is there a way to free() that first part without deallocating the second half?

Please don't suggest realloc() as it allocates a new chunk of memory copy content there and release the previous.(AKAIK).

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

0

No, there is no way you can free() half or part of the dynamically allocated memory. You need to free() it all at a time.

While getting the memory through dynamic memory allocation, you basically get a pointer. You need to pass the exact pointer to free(). Passing a pointer to free() which is not returned by malloc() or family, is undefined behaviour.

FYI, see this related answer.

over 4 years ago · Santiago Trujillo Denunciar

0

realloc() isn't required to copy and a good implementation avoids unnecessary copies. You should really rely on that. (to clarify: for performance reasons, of course. Always assume an implementation may take a copy)

#include <stdlib.h>
#include <stdio.h>

int main()
{
    void *test1 = malloc(16);
    void *test2 = realloc(test1, 8);
    free(test2);

    printf("malloc: %x -- realloc: %x\n", test1, test2);
    return 0;
}

example output:

malloc: 4779c0 -- realloc: 4779c0

over 4 years ago · Santiago Trujillo Denunciar

0

The malloc(3) API doesn't allow this, other than with realloc(3). In common implementations, shrinking with realloc (usually?) won't trigger a copy, and esp. not if the buffer was large.

If you really want to be able to guarantee non-copying, implement your own allocator on top of POSIX mmap(2) / munmap(2). You can unmap part of a mapping without affecting the pages that weren't in the address range given.

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