此文记录了 各种耐人寻味的BUG

此BUG的定位, 耗时5天

栈数值覆盖

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
[root@localhost source]# cat main.c
#include "string.h"
#include "stdio.h"

int fun_B(int a, int b, void* context)
{
char *str = (char*)context;

const char *p = "World Hello World Hello";

strncpy(str, p, strlen(p));

return 0;
}

int fun_A(int a, int b, int (*callback)(int a, int b, void *context), void *context)
{

callback(a, b , &context);

printf("a=%u b=%u\n", a ,b);

return 0;
}

int main(int size, char **list)
{
char str[] = "Hello World";

fun_A(1, 2,fun_B, str);

return 0;
}

[root@localhost source]#

编译 & 运行

1
2
3
[root@localhost source]# gcc main.c  &&  ./a.out
a=7302252 b=1699225700
[root@localhost source]#

符号位

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
[root@localhost source]# cat main.c
#include <stdlib.h>
#include <stdio.h>

struct test {
int x : 1;
int y : 31;
};

int main()
{
struct test t ;
t.x = 1;

if(1 == t.x)
{
printf("1\n");
}
else
{
printf("0\n");
}

return t.x;
}


[root@localhost source]#
[root@localhost source]# gcc main.c && ./a.out ; echo $?
0
255
[root@localhost source]#
[root@localhost source]#

C++的函数重载

问题 找不到add符号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@localhost ~]# cat a.c
extern "C" {
int add(int *a, int *b);

}

int add(const int *a, int *b)
{
return *a + *b;
}
[root@localhost ~]# g++ -c a.c ; nm -Aa a.o
a.o:0000000000000000 a a.c
a.o:0000000000000000 b .bss
a.o:0000000000000000 n .comment
a.o:0000000000000000 d .data
a.o:0000000000000000 r .eh_frame
a.o:0000000000000000 n .note.GNU-stack
a.o:0000000000000000 t .text
a.o:0000000000000000 T _Z3addPKiPi
[root@localhost ~]#

解决 函数的申明不一致

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@localhost ~]# cat a.c
extern "C" {
int add(int *a, int *b);

}

int add(int *a, int *b)
{
return *a + *b;
}
[root@localhost ~]# g++ -c a.c ; nm -Aa a.o
a.o:0000000000000000 a a.c
a.o:0000000000000000 T add
a.o:0000000000000000 b .bss
a.o:0000000000000000 n .comment
a.o:0000000000000000 d .data
a.o:0000000000000000 r .eh_frame
a.o:0000000000000000 n .note.GNU-stack
a.o:0000000000000000 t .text
[root@localhost ~]#