Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!