I need to read some bytes from a socket stream.
No i do a expanding buffer like this:
long curbufsize = 1024*24;
long expand = 1024*24;
void *buf = xmalloc(curbufsize);
void *buf_ptr_start = buf;
char mem[1024*24];
while (rc = my_read_from_stream(handle, mem, sizeof(men)) {
len = (int)buf-((int)buf_ptr_start+rc);
if(curbufsize < len) {
curbufsize+=expand;
xrealloc(buf_ptr_start, curbufsize);
}
memcpy(buf, mem, rc);
}
where should i use size_t and long/int? Should the buffersize be a size_t?
Should i better write for the new len calculation:
len = (size_t)buf-((size_t)buf_ptr_start+rc);
Any other optimization?
Thanks
Using
intthis way is incorrect sinceintmay be smaller than the pointer size of your system and will thus lead to truncation. I’d usesize_tto keep track of your current buffer size and there’s no need for any pointer arithmetic.The reallocation is also completely broken. Why are you calling
xrealloc()and then ignoring the return value. That’s like a leaking version offree()!You could write it something like this: