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:
realloc
can modify the location to which buffer
points. But you fail to modify p
accordingly and it is left pointing into the previous buffer. That's clearly an error.while
loop need not terminate and could run off the end of the buffer. This is the most likely cause of your segmentation fault.realloc
is wrong. If the call to realloc
fails then you can no longer free
the original buffer. You should assign the return value of realloc
to a temporary variable and check for errors before overwriting the buffer
variable.free
on the pointer p
. Since that is meant to point into the block owned by buffer
, you call free
on buffer
alone.