Fork me on GitHub

随笔 - 997  文章 - 5  评论 - 181  阅读 - 300万 

  今天调试代码中,遇到了一个比较奇怪的打印,dump出来的数据只有前四位有值,其他后面的都为零。

出于直觉,应该是内存没有申请到。仔细核对代码之后,果真发现了一个语法错误,就是使用指针的指针时

,对申请到的内存取址错误,函数如下:

  void buff_alloc_check(unsigned char **buff, unsigned int len)

使用方法:

        unsigned char *ibuff = NULL;
        buff_alloc_check(ibuff,ilen);

奇怪的是,系统针对这个并没有报错,后来分析ARM系统发现,这个小系统的检查有关系,我所用的小系统没有

此项检查。

  在Linux上写了一个验证程序,发现是编译不过的。说明不同的系统对编译语法的检查是不一样的。在这里,

暴露了自身在基础上的薄弱,C语言基础仍旧不够好,这个以后要多加;练习。

  为了防止再犯类似的错误,我就在Linux上重新实现了一遍,这样加深理解吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <string.h>
#include <assert.h>
 
#define BUFF_SIZE 2048
 
static unsigned char iarray[BUFF_SIZE];
 
unsigned int ibuff_used = 0;
 
unsigned int buff_alloc_free()
{
 
        return BUFF_SIZE - ibuff_used;
}
 
void buff_alloc_check(unsigned char **buff, unsigned int len)
{
        if(len > buff_alloc_free())
        {
        printf("alloc fialed len:%d freed:%d\n\t",len,buff_alloc_free());
        assert(len > buff_alloc_free());
        }
 
        *buff = iarray + ibuff_used;
        ibuff_used += len;
}
void HexDump(char *buf,int len,int addr)
{
    int i,j,k;
    char binstr[80];
 
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%08x -",i+addr);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            printf("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        printf("%s\n",binstr);
    }
}
 
int main()
{
        unsigned char *ibuff = NULL;
        int ilen = BUFF_SIZE - 1;
        for(int icnt = 0; icnt < BUFF_SIZE; icnt++)
        {
                iarray[icnt] = icnt % 0xFF;
        }
 
        buff_alloc_check(&ibuff,ilen);
        HexDump(ibuff,ilen,(int)ibuff);
 
        return 0;
}

 

posted on   虚生  阅读(496)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示