#include <stdio.h>
#include <stdlib.h>
int main() {
void *malloc(size_t size);
char *ptr, *retval;
ptr = (char *)calloc(10, sizeof(char));
if (ptr == NULL)
printf("calloc failed\n");
else
printf("calloc successful\n");
retval = realloc(ptr, 5);
if (retval == NULL)
printf("realloc failed\n");
else
printf("realloc successful\n");
free(ptr);
free(retval);
}
here is my code the error arises at line 14, it says
invalid conversion from “void*” to “char*”
You could just caast the result of the realloc to (char*) like you do with the malloc.
Ironically though what you have written is perfectly legal “C” code … just not C++ where you require the cast. So you might also try setting your compiler to compile the code as “C” as you aren’t doing any C++ and that would equally solve the issue. That said the above modification is also perfectly legal C … so would compile under C++ and C.
Edit: As softy rightly points out you realloc ptr and store the pointer location into retval which means that ptr is, potentially, pointing at invalid memory and you should NOT free it. At best you free the same memory twice, at worst you call free on memory that has already been freed (by realloc). Either way it is bad ™. As it is you are invoking some serious “undefined behaviour”.