I’m trying reallocate more 256 bytes to buffer on each loop call. In this buffer, I will store the buffer obtained from read().
Here is my code:
#define MAX_BUFFER_SIZE 256
//....
int sockfd = socket( ... );
char *buffer;
buffer = malloc( MAX_BUFFER_SIZE );
assert(NULL != buffer);
char *tbuf = malloc(MAX_BUFFER_SIZE);
char *p = buffer;
int size = MAX_BUFFER_SIZE;
while( read(sockfd, tbuf, MAX_BUFFER_SIZE) > 0 ) {
while(*tbuf) *p++ = *tbuf++;
size = size + MAX_BUFFER_SIZE; // it is the right size for it?
buffer = realloc(buffer, size);
assert(NULL != buffer);
}
printf("%s", buffer);
free(tbuf);
free(p);
free(buffer);
close(sockfd);
But the above code returns segment fault. Where am I wrong?
These are the problems that are apparent to me:
realloccan modify the location to whichbufferpoints. But you fail to modifypaccordingly and it is left pointing into the previous buffer. That’s clearly an error.whileloop need not terminate and could run off the end of the buffer. This is the most likely cause of your segmentation fault.reallocis wrong. If the call toreallocfails then you can no longerfreethe original buffer. You should assign the return value ofreallocto a temporary variable and check for errors before overwriting thebuffervariable.freeon the pointerp. Since that is meant to point into the block owned bybuffer, you callfreeonbufferalone.