sscanf引发的Heap corruption detected error问题——有待完美解决
来源:互联网 发布:善存 多维 佳维 知乎 编辑:程序博客网 时间:2024/06/06 08:59
抛出问题
今天在写程序的时候遇到了一个以前没有暴露出来的问题,问题如题目所示。下面写了一个小的测试程序,如下:
#include <stdio.h>#include <stdlib.h>int main(){unsigned char *ua = (unsigned char*)malloc(sizeof(unsigned char) * 3);char line[40] = "177 100 88";sscanf(line, "%hhu %hhu %hhu", &ua[0], &ua[1], &ua[2]);printf("ua[3] = {%hhu, %hhu, %hhu}\n", ua[0], ua[1], ua[2]);if (ua){free(ua);}return 0;}
在debug模式下会有如下错误:
从提示可以看出来,是内存那块出了问题。大体意思是 C运行时检测到应用程序在堆缓存后写入了内存。
解决问题方案
经过调试,我发现,我在程序中分配的内存大小是3*sizeof(unsigned char)=3个字节,但是用sscanf写入的是6个字节的内存大小,所以最后释放内存的时候就会释放6个字的大小,就有了上面的错误。
但是如果我用%c的格式写入的时候就不会报这个错误了。这里我想要的是0~255的值,而不是一个字符。把分配的内存大小改为6时就解决了。但总感觉这不是最好的解决办法,希望有高手能指点出不对的地方。
最后完整代码如下:
#include <stdio.h>#include <stdlib.h>//想获得ua的值在0~255之间,而不是一个字符int main(){unsigned char *ua = (unsigned char*)malloc(sizeof(unsigned char) * 6);char line[40] = "177 100 88";sscanf(line, "%hhu %hhu %hhu", &ua[0], &ua[1], &ua[2]);printf("ua[3] = {%hhu, %hhu, %hhu}\n", ua[0], ua[1], ua[2]);if (ua){free(ua);}return 0;}
1 0
- sscanf引发的Heap corruption detected error问题——有待完美解决
- CString引发的Heap corruption detected
- Heap corruption detected error
- Heap corruption detected error
- Heap Corruption Detected Error
- Heap corruption detected error
- Heap corruption detected error
- Error: HEAP CORRUPTION DETECTED
- unknown heap name引发Error detected (LME288)从而Unable to perform link问题的解决
- coco2dx heap corruption detected by dlfree 闪退的问题
- “HEAP CORRUPTION DETECTED”错误原因与解决
- heap corruption detected可能的原因
- Heap Corruption Detected 错误的原因分析
- Heap Corruption detected
- heap corruption detected
- Heap Corruption Detected
- C++ Heap corruption detected
- HEAP CORRUPTION DETECTED
- Apache部署django项目
- Hadoop伪分布式配置试用+eclipse配置使用
- HDU 4493 Tutor(数学啊 )
- 第一次校赛
- 如何在windows中安装和设置mysql解压缩版
- sscanf引发的Heap corruption detected error问题——有待完美解决
- eclipse安装hadoop插件及配置
- 实习复习的一些知识
- python pip的安装
- hadoop程序运行
- .Net GridView异步刷新
- [leetcode][list][two pointers] Remove Nth Node From End of List
- Django的是如何工作的
- 实习面试问到的一些知识