Its broken and crashes horribly? A bit harsh matey. I was working from memory (no pun intended).
You are correct though a check on the return value of realloc should be made. If realloc fails then you are out of memory and so are screwed anyway!
Oh, and dont forget to free buf2, or it may break and crash horribly taking the world with it etc..
// Could do char buf1 here and pass &buf1 to function
char buf1[1];
// Initialise to 0 elements
int size=0;
// Initialise to NULL so realloc works properly!
// Could do "char *buf2 = NULL;", its the same thing!
char buf2[] = NULL;
while (recv(new_fd,buf1,sizeof(buf1),0) && (size>0))
{
// Increase size of array
size++;
// Reallocate buffer (+1 for terminator!)
if realloc(buf2,(size+1)*(sizeof(char))>0)
{
// Copy character (-1 because array starts at 0)
buf2[size-1] = buf1[0];
// Reset terminator
buf2[size] = '\0';
// Print status
printf("size: %d\nbuf2: %s\n",size,buf2);
}
else
{
// realloc failed
printf("No more memory!\n");
// force loop exit
size = -1;
}
}
free(buf2);