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