Search code examples
clinuxsocketsmemcpyrealloc

realloc: invalid next size; memcpy


I have code like this:

char buf[128];
char *data = NULL;
char *temp = NULL;

int full = 0;

int n = 0;

do {
     bzero(buf, sizeof(buf));
     n = recv(newsock, buf, sizeof(buf), 0);

     full += sizeof(buf);

     if(n != 0)
          temp = realloc(data, sizeof(buf));

     if(temp != NULL) {
          data = temp;
     } else {
         // error
     }

     memcpy(data + (full - sizeof(buf)), buf, sizeof(buf));

     printf("%s\n",data);
} while(n > 0);

In this code i try get some data from socket to buffer and put this data into the memory. But i have problem. On third iteration of while cycle i get message like this:

*** glibc detected *** ./server: realloc(): invalid next size: 0x09a4c008 ***

When i remove memcpy() function everything alright, but how can i put data into memory? What is wrong?


Solution

  • The problem is that you keep adding to data, but you don't expand its memory. The line

    temp = realloc(data, sizeof(buf));
    

    always allocates 128 bytes. You need to update that that in every iteration it will allocate more. Maybe you intended to do this insead:

    temp = realloc(data, full);
    

    ?