开发者

What var type you use on growing buffers [closed]

开发者 https://www.devze.com 2023-04-12 20:47 出处:网络
This ques开发者_开发知识库tion is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not
This ques开发者_开发知识库tion is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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 int this way is incorrect since int may be smaller than the pointer size of your system and will thus lead to truncation. I'd use size_t to 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 of free()!

You could write it something like this:

size_t len = 0;
size_t size = 0;
size_t expand = 1024*24;
char *buf = NULL;
char *newbuf;
char mem[1024*24]; 
while (rc = my_read_from_stream(handle, mem, sizeof(men)) {
    if (size < len+rc) {
        while (size < len+rc)
        {
            size += expand;
        }
        newbuf = xrealloc(buf, size);
        if (!newbuf)
        {
            free(buf);
            return ERROR_MEMORY_ALLOCATION_FAILED;
        }
        buf = newbuf;
    }
    memcpy(buf+len, mem, rc);
    len += rc;
}


You can look in the header file that declares xmalloc; the type of its parameter must be right there. Though by the look of your code you are not trying to write a portable application, so you probably don't need to worry about such choices.

Just fix the bugs.

Edit: seeing that you talk about optimization, take into account that int might be faster than size_t (most probably it isn't) - profile the two variants and choose the fastest (or acknowledge that they have the same efficiency).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号