博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
When a function requires a pointer, it's not only an out value...
阅读量:4970 次
发布时间:2019-06-12

本文共 2096 字,大约阅读时间需要 6 分钟。

Today one of my fellow encountered a bug. He was working on a server/client app, the server and client use zlib to compress telegram before sending and after receiving. The programs work fine in debug build, however they failed to send and receive in release build.

As a few minutes' investigation, I relized the programs work fine before he introduces the compression, so I looked into his compression module. He implemented a pretty module to accept data pieces and pack them, and compress, like this:

class data_packer{public:    data_packer();    void add(const char* buf, int len);    void pack();    int compressed_size() const;    const char* compressed_data() const;private:    char _data[100000];    char _compressed[100000];    int _size;     int _compressed_size;};

other parts are not related to this bug, so i just show the functions caused the problem:

data_packer::data_packer()    : _size(0){}void data_packer::pack(){    // use zlib's compress function    compress(_compressed, &_compressed_size, _data, _size);}

As you can see, the _compressed_size is not initialized. However many prople may say it's OK because the compress function asks for a pointer, so that it wants to send out the compressed size. Yes it's true, but that's only half of it. In fact, the compress function uses 2nd argument as in/out parameter. It uses the 2nd argument to determine whether the provided buffer (1st argument) is big enough. And here is the fact that, my fellow is only lucky enough in debug build because the uninitialized _compressed_size member is larger than the truely required byte count, while in release build it's not. OK, case is closed, modify the pack method like this and the problem is resolved.

void data_packer::pack(){    _compressed_size = 1000000;    compress(...);}

Actually this is not the best practise. In production code, a call to compressBound() to determine the safe buffer size is recommended. Also, this bug shows us, when you send a pointer to a function, you'd better check whether the function uses the value!

转载于:https://www.cnblogs.com/wane/p/3460629.html

你可能感兴趣的文章
codeforces div 313
查看>>
四则运算缓冲流
查看>>
MySQL中间件之ProxySQL(8):SQL语句的重写规则
查看>>
Perl数据序列化和持久化(入门):Storable模块
查看>>
log4j中存在日志无法打印问题解决
查看>>
Netty中的Channel之数据冲刷与线程安全(writeAndFlush)
查看>>
c#中的重写(override)和重载(overload)的区别
查看>>
高效使用数码相机的诀窍
查看>>
mysql之内连接,外连接(左连接,右连接),union,union all的区别
查看>>
学习笔记 : python 文件操作
查看>>
html5 3D圣诞树源码
查看>>
json-server基本使用
查看>>
常用的几种距离的优劣
查看>>
图灵2010.11书讯
查看>>
项目经理如何有效地进行项目沟通?
查看>>
【原创】linux mint 17.3 kvm 安装windows7虚拟机
查看>>
二进制集合枚举子集
查看>>
Android GridView 指定行数,动态行宽,占满空间
查看>>
极大似然估计和最大后验概率
查看>>
(转载)java中判断字符串是否为数字的方法的几种方法
查看>>