'Should I use free() when realloc fails?
I wondered if I have a memory leak, I don't know whether I should use free() when realloc fails or it does that automatically.
for example, I have a dynamic array of chars, each time I'm reaching the end of it from input, I'm adding more memory using realloc. I'm saving the last address just in case the realloc fails.
int cntan = 0;
char *p = (char *)malloc(MEM_SIZE * sizeof(char));
char *q = p; /*backup pointer*/
int c;
long current = 0, last = MEM_SIZE - 1;
while ((c = getchar()) != EOF)
{
if (current >= last) /* if reached last bit */
{
q = p;
p = (char *)realloc(q, last + (MEM_SIZE * sizeof(char))); /* attempting to add more bits */
if (p == NULL)
{
printf("Memory allocation failed, printing only stored values \n");
return q;
}
last += MEM_SIZE;
}
p[current] = c;
++current;
if (isalnum(c)) /* checking if current char is alpha-numeric */
cntan++;
}
in this example, I wonder I should free(p) if p==NULL
whole code if someone interested: Pastebin
Solution 1:[1]
You should free() the original pointer, not the one returned by realloc(). Passing NULL to free() won’t do anything.
To clarify: the pointer returned by realloc() on success may not be the same as the original pointer.
Solution 2:[2]
Other problems with code:
Length unknown
return q; returns the pointer, yet the caller lacks information about how big an allocation (current).
Conceptually wrong size calculation
Scaling by sizeof(char)applies to the sum. Makes no difference in this case as sizeof char is always 1.
// last + (MEM_SIZE * sizeof(char))
(last + MEM_SIZE) * sizeof(char)
Missing malloc() check
Code checks the return value of realloc(), but misses checking malloc().
Note: cast not needed. Consider:
// p = (char *)realloc(q, last + (MEM_SIZE * sizeof(char)));
p = realloc(q, sizeof q[0] * (last + MEM_SIZE));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
