在工作中我们可能会遇到这样的情况,我们知道有个大小为100字节的变量存在内存未释放的情况,但是很难从数量庞大的代码中寻找该结构体。那我们有什么方法可以快速找到么?

我们在gcc编译时通常会添加一些编译选项用来保证程序的质量,今天我们就用-Wlarger-than=x的选项来查找我们需要的结构体。

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
#include <stdio.h>

typedef struct
{
int a;
int b;
char c;
}A;

typedef struct
{
int a;
char b;
}B;

typedef struct
{
short int a;
char b;
short int c;
}C;

int main(int argc,char *argv[])
{
A a;
B b;
C c;

return 0;
}

1
2
3
4
5
6
[root@smart 29_switch]# gcc -o temp temp.c -Wlarger-than=5
temp.c: In function ‘main’:
temp.c:25: warning: size of ‘a’ is 12 bytes
temp.c:26: warning: size of ‘b’ is 8 bytes
temp.c:27: warning: size of ‘c’ is 6 bytes
[root@smart 29_switch]#

从上述编译过程我们可以看出,变量c的大小为6字节,从而我们可以得到相应的结构体是哪一个。