Search code examples
csocketsmallocfreerealloc

Using free with realloc


i am trying to use realloc for synamically allocating memory to array while reading from socket .. evrything is working fine but it is giving error when i am using free in main. i actually need to get data in usr_data and send it to different functions for processing.

*** glibc detected *** free(): invalid next size (fast): 0x083fc008 ***
Aborted (core dumped)

Here is the function:

int read_from_socket(int connfd,char **usr_str)
{
printf("\nusr_data : %s\n",*usr_str);
int count = 0, bytesread = 0;
char *temp;
char buf[MAX] = {0};
while((bytesread = read(connfd,buf,BLOCKSIZE))>0)
{
    temp = NULL;
    count = count + bytesread;
    temp = (char *)realloc(*usr_str, count);
    if(NULL == temp)
    {
        printf("\nMemory Error\n");
        return FAILURE;
    }
    *usr_str = temp;
    printf("\nadd in: %lu",*usr_str);
    memcpy(((*usr_str) + count - bytesread),buf, MAX);
    printf("\nadd in2: %lu",*usr_str);
    if((*usr_str)[count-1] == '$')
    {
       (*usr_str)[count-1] = '\0';
       printf("\nData received: %s\n",*usr_str);
       printf("\nadd in2: %lu",*usr_str);
       break;
    }
}
}

AND HERE is The code i am using in main

for(;;)
{
printf("I am waiting-----Start of Main Loop\n");
len=sizeof(cliaddr);
connfd=accept(sd,(struct sockaddr*)&cliaddr,&len);
if ( connfd < 0)
{
    if (errno == EINTR)
    printf("Interrupted system call ??");
    continue;
}
printf("Connection from %s\n",inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)));
while(1)
{
    usr_data = NULL;
    read_from_socket(connfd,&usr_data);
    printf("\nusr_dat: %s    %lu\n",usr_data,usr_data);
    if(!strcmp(usr_data,"exit"))
    {
        break;
    }
    printf("\nadd: %lu\n",usr_data);
    free(usr_data);
}
close(connfd);
printf("\nFINISHED SERVING ONE CLIENT\n");
}

actually the server keeps on running in the read loop until it gets exit from user...

can any one point out why.. glibc error with free()


Solution

  • memcpy(((*usr_str) + count - bytesread),buf, bytesread);
    

    should do it. If bytesread is less than MAX your version copies beyond the end of the allocated buffer