1. any problem if i dynamically allocate memory and use only a small part of it?
2. can i free the dynamic memory after each time the function is executed?

Dani AI

Generated

Short answer: allocating a larger block and using only part of it is not intrinsically wrong — malloc gives you at least the bytes you asked for, and using a smaller portion is safe as long as you never read or write past the requested size. Ownership and lifetime are the real issues: whoever owns the pointer is responsible for freeing it.

As noted, freeing right after a return is a logic error because that code is never reached. If a function returns a heap pointer, the caller must free it; if the function does all the work internally and does not expose the pointer, the function should free before returning. Example ownership pattern:

char *make_buffer(size_t n) {
    char *p = malloc(n);
    if (!p) return NULL;
    memset(p, 0, n);
    return p;        /* caller owns p */
}

void use_buffer(void) {
    char *b = make_buffer(256);
    if (!b) return;
    /* use b here */
    free(b);         /* release when done */
}

Practical tips and cautions:

  • Check malloc/realloc returns for NULL.
  • If you over-allocate but the buffer is long‑lived, consider realloc to shrink it to the true size (check the return before replacing the original pointer).
  • Avoid double-free and use-after-free bugs: free exactly once, and don’t free pointers that were not returned by malloc/calloc/realloc.
  • If performance matters, reuse a single buffer or use an allocation pool instead of repeated malloc/free.
  • If you need zeroed memory, use calloc or memset after malloc.
  • Use tools (Valgrind, ASan) to find leaks and invalid access.

In short: using less than you allocated is fine; just make ownership explicit (who frees) and guard against common UB (null returns, overruns, double frees). This addresses ’s questions and expands on ’s correction about freeing after a return.

Recommended Answers

All 4 Replies

1. No
2. Yes, providing you reallocate the memory before attempting to use it. .

is the position of 'free a' in pgm correct?

function(variables)
{
a=malloc(...);
....
return a;
free a; //is this the correct position to free a?
}

No -- reverse the order of lines 5 and 6. As it is, line 6 will never get executed because the function exits on line 5.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.