Hi everyone,
i hope someone could run over my code to see what im doing wrong...
this is not the total code but enough to see the problem.. i hope..
i have a function which reads from a socket and and dynamicly manages memory for a buffer. This buffer is first allocated in the main method. the problem is that i get a segfault sometimes in the realloc function in the main method just after "before realloc in entry ... " and sometimes in the strcat function To my knowledge is this buffer always big enough to contain the string
hope someone can help me...
my code looks like this..
Code:
# define BUFFER 1024
static xmlString = NULL;
static _2k =2
main(){
/* if pointer points to other than null than this service has been called before so reset and reuse it */
_2k = 2;
if (xmlString != NULL ){
deb_log(0, "%s", "before: realloc in entry");
ptr = (void * )realloc(xmlString, (_2k * RS_BUFFER));
if ( ptr == NULL ){
realloc(xmlString, 0 );
return MALLOC_ERROR + MV + "Error while allocating memory";
}
xmlString = ptr;
deb_log(0, "%s", "after: realloc in entry");
memset(xmlString, 0, (_2k * RS_BUFFER));
deb_log(0, "%s", "after: memset");
receiveHttpMsg(&xmlString, fd );
}
int receiveHttpMsg(char ** buf, int fd){
int totalBytesRcvd;
void * tmp;
char * readBuffer = (char * ) calloc(1, BUFFER);
int bytesRcvd = 1; /* Bytes read in single recv() */
/* Receive response from the server */
printf("Received: ");
while (bytesRcvd > 0) {
/* Receive up to the buffer size (minus 1 to leave space for
a null terminator) did this in loop because otherwise the whole message could not be read
*/
if ((bytesRcvd = recv(fd, readBuffer, (BUFFER -1) , 0)) > 0){
totalBytesRcvd += bytesRcvd; /* total bytes read in loop*/
readBuffer[bytesRcvd] = '\0';
printf(" [%d][%d][%d]\n", strlen(*buf), strlen(readBuffer), _2k * RS_BUFFER);
if ( (strlen(*buf) +strlen(readBuffer) -1) > _2k * RS_BUFFER){
_2k++;
tmp = (void * )realloc(*buf, (_2k * RS_BUFFER));
if ( tmp == NULL ){
printf("error while reallocating .. \n");
realloc(*buf, 0 );
free(readBuffer);
return -1;
}
*buf = tmp;
(*buf)[totalBytesRcvd]= '\0';
printf(" buffer enlarged [%d]\n", strlen(*buf));
}
/* STRCAT SEGFAULT*/
deb_log(0, "%s", "tocopy");
strcat(*buf, readBuffer);
deb_log(0, "%s", "copy--done");
/* memset(readBuffer, 0 , BUFFER); */
}
/* host closed connection so we cleanup socket */
else{
printf("close connection \n");
close(fd);
free(readBuffer);
break;
} /* end else */
} /* end while */
}