数据结构(十三):附录 —— 全部实验代码与复现指南

本篇收录系列全部 11 个实验程序的完整可编译源码。每个程序都是独立文件,gcc 一条命令编译运行;第 12 篇的 ds12 需要 FreeRTOS 内核源码参与编译(与 FreeRTOS 笔记系列的实验库共仓)。全部在本机 gcc 16.2.0 实测通过。

系列目录

  1. C 程序的内存地图
  2. 栈与函数调用
  3. 堆与动态内存
  4. 结构体内存对齐
  5. 结构体进阶:union、位域与柔性数组
  6. 数组与动态数组:手写简易 vector
  7. 单链表
  8. 双向链表与循环链表
  9. 栈与队列
  10. 哈希表
  11. 真工程实战:解读 FreeRTOS list.c
  12. 手写线程安全队列
  13. 附录:全部实验代码与复现指南(本篇)

一、目录结构与编译命令

1
2
3
4
ds-lab/
├── ds01_memory_map.c … ds10_hash.c # 纯 C 实验:gcc 直接编译
├── ds12_tsqueue.c # FreeRTOS 实验:需内核源码
└── (FreeRTOS-Kernel 在 ../freertos-lab/FreeRTOS-Kernel)

纯 C 实验的编译命令(以 ds01 为例,其余同构):

1
2
gcc -O0 -g -Wall -Wextra ds01_memory_map.c -o ds01_memory_map.exe
.\ds01_memory_map.exe

ds02 有两种运行模式:.\ds02_stack_frames.exe frames(观察栈帧)与 .\ds02_stack_frames.exe boom(故意爆栈,退出码 0xC00000FD)。

ds12(FreeRTOS)的编译命令:

1
2
3
4
5
6
7
8
9
10
11
gcc -O0 -g -Wall -Wextra -D_WIN32_WINNT=0x0601 `
-I ..\freertos-lab\FreeRTOS-Kernel\include `
-I ..\freertos-lab\FreeRTOS-Kernel\portable\MSVC-MingW `
-I ..\freertos-lab\demo01 `
ds12_tsqueue.c `
..\freertos-lab\FreeRTOS-Kernel\tasks.c ..\freertos-lab\FreeRTOS-Kernel\list.c `
..\freertos-lab\FreeRTOS-Kernel\queue.c ..\freertos-lab\FreeRTOS-Kernel\timers.c `
..\freertos-lab\FreeRTOS-Kernel\event_groups.c ..\freertos-lab\FreeRTOS-Kernel\stream_buffer.c `
..\freertos-lab\FreeRTOS-Kernel\portable\MSVC-MingW\port.c `
..\freertos-lab\FreeRTOS-Kernel\portable\MemMang\heap_4.c `
-o ds12_tsqueue.exe -lwinmm

-I ..\freertos-lab\demo01 借用了 FreeRTOS 笔记系列的 FreeRTOSConfig.h(configUSE_TASK_NOTIFICATIONS=1 等已配好)。

二、实验 1:C 程序的内存地图(ds01_memory_map.c)

预期现象:.text/.rdata/.data/.bss 地址同族、堆另起一段、栈在更高处;.bss 自动清零。

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

int g_initialized = 42; /* .data:已初始化的全局变量 */
int g_zeroed[ 100 ]; /* .bss:未初始化(零值)全局变量 */
static int s_static = 7; /* .data:静态变量 */
const int g_const = 123; /* .rdata:只读数据段 */

int main( void )
{
static int s_local_static = 9; /* .data:局部静态变量 */
int l_stack = 1; /* 栈 */
char l_buf[ 16 ] = "stack"; /* 栈 */
int * p_heap1 = ( int * ) malloc( 64 ); /* 堆 */
int * p_heap2 = ( int * ) malloc( 64 ); /* 堆 */
const char * p_literal = "hello, rodata"; /* .rdata:字符串字面量 */

printf( "== C 程序内存地图 ==\r\n" );
printf( ".text 代码段 main 函数 : %p\r\n", ( void * ) main );
printf( ".rdata 字符串字面量 : %p -> \"%s\"\r\n", ( void * ) p_literal, p_literal );
printf( ".rdata 常量 g_const : %p (值=%d)\r\n", ( const void * ) &g_const, g_const );
printf( ".data 已初始化全局 g_init : %p (值=%d)\r\n", ( void * ) &g_initialized, g_initialized );
printf( ".data 静态变量 s_static : %p (值=%d)\r\n", ( void * ) &s_static, s_static );
printf( ".data 局部静态 s_local_static : %p (值=%d)\r\n", ( void * ) &s_local_static, s_local_static );
printf( ".bss 零值全局 g_zeroed[0] : %p (值=%d,自动清零)\r\n", ( void * ) &g_zeroed[ 0 ], g_zeroed[ 0 ] );
printf( "堆 第 1 次 malloc(64) : %p\r\n", ( void * ) p_heap1 );
printf( "堆 第 2 次 malloc(64) : %p\r\n", ( void * ) p_heap2 );
printf( "栈 局部变量 l_stack : %p\r\n", ( void * ) &l_stack );
printf( "栈 局部数组 l_buf : %p\r\n", ( void * ) l_buf );

free( p_heap1 );
free( p_heap2 );
return 0;
}

三、实验 2:栈与函数调用(ds02_stack_frames.c)

预期现象:frames 模式栈帧地址每层下降约 80 字节;boom 模式爆栈退出码 0xC00000FD。

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

static void vRecurse( unsigned long ulDepth, unsigned long ulMax )
{
volatile char cFrame[ 32 ]; /* 每层栈帧里放一点东西 */
cFrame[ 0 ] = ( char ) ulDepth;

if( ( ulDepth == 1 ) || ( ( ulDepth % 2500 ) == 0 ) )
{
printf( "depth %6lu, frame address = %p\r\n",
ulDepth, ( void * ) cFrame );
}

if( ( ulMax != 0 ) && ( ulDepth >= ulMax ) )
{
return;
}
vRecurse( ulDepth + 1, ulMax );
}

int main( int argc, char ** argv )
{
if( ( argc > 1 ) && ( strcmp( argv[ 1 ], "boom" ) == 0 ) )
{
printf( "mode: overflow —— 无上限递归,直到栈溢出...\r\n" );
vRecurse( 1, 0 ); /* ulMax=0 表示不设限 */
printf( "survived?!\r\n" ); /* 理论上到不了这里 */
}
else
{
printf( "mode: frames —— 递归 20000 层观察栈帧地址\r\n" );
vRecurse( 1, 20000 );
printf( "done.\r\n" );
}
return 0;
}

四、实验 3:堆与动态内存(ds03_heap.c)

预期现象:p1/p2 地址相同(free 复用);泄漏 128MB 后可用物理内存减少约 132MB。

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

static void print_avail( const char * pcTag )
{
MEMORYSTATUSEX xM;
xM.dwLength = sizeof( xM );
GlobalMemoryStatusEx( &xM );
printf( "%s 可用物理内存 = %lu MB\r\n", pcTag,
( unsigned long ) ( xM.ullAvailPhys / ( 1024 * 1024 ) ) );
}

int main( void )
{
int * p1 = ( int * ) malloc( 100 );
printf( "p1 = malloc(100) -> %p\r\n", ( void * ) p1 );
free( p1 );
int * p2 = ( int * ) malloc( 100 );
printf( "p2 = malloc(100) -> %p (和 p1 一样:刚释放的块被复用)\r\n", ( void * ) p2 );

print_avail( "泄漏前" );
for( int i = 0; i < 128; i++ )
{
char * pLeak = ( char * ) malloc( 1024 * 1024 ); /* 1 MB,绝不 free */
if( pLeak != NULL )
{
memset( pLeak, 1, 1024 * 1024 );
}
}
print_avail( "泄漏 128 MB 后" );

char * pGood = ( char * ) malloc( 1024 );
if( pGood != NULL )
{
memset( pGood, 0, 1024 );
printf( "正常流程:malloc -> 使用 -> free,地址 %p\r\n", ( void * ) pGood );
free( pGood );
pGood = NULL;
printf( "free 后指针置 NULL:野指针的第一道防线\r\n" );
}
return 0;
}

五、实验 4:结构体内存对齐(ds04_alignment.c)

预期现象:sizeof = 1 / 8 / 24 / 8 / 16 / pack(1)=5;offsetof(B, i) = 4。

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

struct A { char c; };
struct B { char c; int i; };
struct C { char c; double d; char c2; };
struct D { int i; char c; short s; };
struct E { char c1; struct B b; char c2; };

#pragma pack(push, 1)
struct Packed { char c; int i; };
#pragma pack(pop)

int main( void )
{
printf( "sizeof(struct A) = %2zu\r\n", sizeof( struct A ) );
printf( "sizeof(struct B) = %2zu\r\n", sizeof( struct B ) );
printf( "sizeof(struct C) = %2zu\r\n", sizeof( struct C ) );
printf( "sizeof(struct D) = %2zu\r\n", sizeof( struct D ) );
printf( "sizeof(struct E) = %2zu\r\n", sizeof( struct E ) );
printf( "sizeof(struct Packed) pack(1) = %zu\r\n", sizeof( struct Packed ) );
printf( "offsetof(B, c) = %zu\r\n", offsetof( struct B, c ) );
printf( "offsetof(B, i) = %zu\r\n", offsetof( struct B, i ) );
printf( "struct B arr[2] 总大小 = %zu\r\n", sizeof( struct B ) * 2 );
return 0;
}

六、实验 5:union、位域与柔性数组(ds05_struct_advanced.c)

预期现象:字节序 04 03 02 01(小端);位域 0xEAAD;柔性数组 malloc(13) 装下 10 字符。

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

struct Bits
{
uint32_t a : 3;
uint32_t b : 5;
uint32_t c : 6;
uint32_t d : 2;
};

struct Msg
{
uint16_t usLen;
char data[];
};

int main( void )
{
union
{
uint32_t ulValue;
unsigned char ucBytes[ 4 ];
} uEndian;
uEndian.ulValue = 0x01020304;
printf( "sizeof(union) = %zu\r\n", sizeof( uEndian ) );
printf( "按字节读 = %02X %02X %02X %02X\r\n",
uEndian.ucBytes[ 0 ], uEndian.ucBytes[ 1 ],
uEndian.ucBytes[ 2 ], uEndian.ucBytes[ 3 ] );

struct Bits xBits;
memset( &xBits, 0, sizeof( xBits ) );
xBits.a = 5; xBits.b = 21; xBits.c = 42; xBits.d = 3;
uint32_t ulRaw;
memcpy( &ulRaw, &xBits, sizeof( ulRaw ) );
printf( "位域原始 uint32 = 0x%04X\r\n", ulRaw );

const char * pcPayload = "hello flex";
size_t xNeed = sizeof( struct Msg ) + strlen( pcPayload ) + 1;
struct Msg * pxMsg = ( struct Msg * ) malloc( xNeed );
pxMsg->usLen = ( uint16_t ) strlen( pcPayload );
memcpy( pxMsg->data, pcPayload, strlen( pcPayload ) + 1 );
printf( "sizeof(struct Msg) = %zu, malloc(%zu), data = \"%s\"\r\n",
sizeof( struct Msg ), xNeed, pxMsg->data );
free( pxMsg );
return 0;
}

七、实验 6:动态数组(ds06_vector.c)

预期现象:容量 0→4→8→16→32,四次扩容地址全变,17 条数据完好。

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

typedef struct
{
int * pData;
size_t xSize;
size_t xCap;
} Vector;

static int iPushBack( Vector * pxV, int iValue )
{
if( pxV->xSize == pxV->xCap )
{
size_t xNewCap = ( pxV->xCap == 0 ) ? 4 : pxV->xCap * 2;
int * pNew = ( int * ) realloc( pxV->pData, xNewCap * sizeof( int ) );
if( pNew == NULL )
{
return -1;
}
printf( " [扩容] 容量 %zu -> %zu, 数据区 %p -> %p\r\n",
pxV->xCap, xNewCap, ( void * ) pxV->pData, ( void * ) pNew );
pxV->pData = pNew;
pxV->xCap = xNewCap;
}
pxV->pData[ pxV->xSize++ ] = iValue;
return 0;
}

int main( void )
{
Vector xV = { 0 };
for( int i = 1; i <= 17; i++ )
{
iPushBack( &xV, i * 10 );
printf( "push %2d -> size=%2zu cap=%2zu data=%p\r\n",
i, xV.xSize, xV.xCap, ( void * ) xV.pData );
}
free( xV.pData );
return 0;
}

八、实验 7:单链表(ds07_slist.c)

预期现象:建链 1→3→7、查找命中、删除 7、反转 3→1,全部正确。

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
int iValue;
struct Node * pxNext;
} Node;

static Node * pxMakeNode( int iValue )
{
Node * pxN = ( Node * ) malloc( sizeof( Node ) );
pxN->iValue = iValue;
pxN->pxNext = NULL;
return pxN;
}

static void vPrintList( const char * pcTag, Node * pxHead )
{
printf( "%-14s: ", pcTag );
for( Node * p = pxHead; p != NULL; p = p->pxNext )
{
printf( "%d -> ", p->iValue );
}
printf( "NULL\r\n" );
}

static void vPushFront( Node ** ppxHead, int iValue )
{
Node * pxN = pxMakeNode( iValue );
pxN->pxNext = *ppxHead;
*ppxHead = pxN;
}

static void vPushBack( Node ** ppxHead, int iValue )
{
Node * pxN = pxMakeNode( iValue );
if( *ppxHead == NULL ) { *ppxHead = pxN; return; }
Node * p = *ppxHead;
while( p->pxNext != NULL ) { p = p->pxNext; }
p->pxNext = pxN;
}

static Node * pxFind( Node * pxHead, int iValue )
{
for( Node * p = pxHead; p != NULL; p = p->pxNext )
if( p->iValue == iValue ) { return p; }
return NULL;
}

static void vDeleteByValue( Node ** ppxHead, int iValue )
{
Node * pxPrev = NULL;
Node * p = *ppxHead;
while( p != NULL && p->iValue != iValue )
{
pxPrev = p;
p = p->pxNext;
}
if( p == NULL ) { return; }
if( pxPrev == NULL ) { *ppxHead = p->pxNext; }
else { pxPrev->pxNext = p->pxNext; }
free( p );
}

static void vReverse( Node ** ppxHead )
{
Node * pxPrev = NULL;
Node * p = *ppxHead;
while( p != NULL )
{
Node * pxNext = p->pxNext;
p->pxNext = pxPrev;
pxPrev = p;
p = pxNext;
}
*ppxHead = pxPrev;
}

int main( void )
{
Node * pxHead = NULL;
vPushBack( &pxHead, 3 );
vPushBack( &pxHead, 7 );
vPushFront( &pxHead, 1 );
vPrintList( "建链后", pxHead );
Node * pxFound = pxFind( pxHead, 7 );
printf( "查找 7: %s\r\n", pxFound ? "命中" : "未找到" );
vDeleteByValue( &pxHead, 7 );
vPrintList( "删除 7 后", pxHead );
vReverse( &pxHead );
vPrintList( "反转后", pxHead );
while( pxHead != NULL )
{
Node * pxNext = pxHead->pxNext;
free( pxHead );
pxHead = pxNext;
}
return 0;
}

九、实验 8:双向链表与循环链表(ds08_dlist.c)

预期现象:哨兵方案下删除不存在的 5 安全返回;循环链表走 12 步回绕。

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>

typedef struct DNode
{
int iValue;
struct DNode * pxPrev;
struct DNode * pxNext;
} DNode;

static DNode * pxSentinel;

static void vDListInit( void )
{
pxSentinel = ( DNode * ) malloc( sizeof( DNode ) );
pxSentinel->iValue = 0;
pxSentinel->pxPrev = pxSentinel;
pxSentinel->pxNext = pxSentinel;
}

static void vDListPushBack( int iValue )
{
DNode * pxN = ( DNode * ) malloc( sizeof( DNode ) );
pxN->iValue = iValue;
pxN->pxPrev = pxSentinel->pxPrev;
pxN->pxNext = pxSentinel;
pxSentinel->pxPrev->pxNext = pxN;
pxSentinel->pxPrev = pxN;
}

static int iDListDelete( int iValue )
{
for( DNode * p = pxSentinel->pxNext; p != pxSentinel; p = p->pxNext )
{
if( p->iValue == iValue )
{
p->pxPrev->pxNext = p->pxNext;
p->pxNext->pxPrev = p->pxPrev;
free( p );
return 1;
}
}
return 0;
}

static void vDListPrint( void )
{
printf( " 正向: 哨兵 <-> " );
for( DNode * p = pxSentinel->pxNext; p != pxSentinel; p = p->pxNext )
printf( "%d <-> ", p->iValue );
printf( "哨兵\r\n" );
printf( " 反向: 哨兵 <-> " );
for( DNode * p = pxSentinel->pxPrev; p != pxSentinel; p = p->pxPrev )
printf( "%d <-> ", p->iValue );
printf( "哨兵\r\n" );
}

int main( void )
{
vDListInit();
vDListPushBack( 3 );
vDListPushBack( 9 );
vDListPushBack( 1 );
vDListPrint();
printf( " 删除 9: %s\r\n", iDListDelete( 9 ) ? "成功" : "未找到" );
printf( " 删除 5: %s\r\n", iDListDelete( 5 ) ? "成功" : "未找到" );
vDListPrint();

/* 循环单链表:头插建环,走 12 步 */
int aiData[ 5 ] = { 5, 4, 3, 2, 1 };
DNode * pxCur = NULL;
for( int i = 0; i < 5; i++ )
{
DNode * pxN = ( DNode * ) malloc( sizeof( DNode ) );
pxN->iValue = aiData[ i ];
pxN->pxNext = pxCur;
pxCur = pxN;
}
DNode * p = pxCur;
while( p->pxNext != NULL ) { p = p->pxNext; }
p->pxNext = pxCur;

printf( " 循环走 12 步: " );
DNode * pxWalk = pxCur;
for( int i = 0; i < 12; i++ )
{
printf( "%d ", pxWalk->iValue );
pxWalk = pxWalk->pxNext;
}
printf( "\r\n" );

while( pxSentinel->pxNext != pxSentinel )
{
DNode * pxN = pxSentinel->pxNext;
pxSentinel->pxNext = pxN->pxNext;
free( pxN );
}
free( pxSentinel );
return 0;
}

十、实验 9:栈与队列(ds09_stack_queue.c)

预期现象:栈 LIFO;循环队列 tail 回绕(60 落在物理下标 0);head=tail=2 且 count=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
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_CAP 5

static int aiStack[ 8 ];
static int iTop = -1;
static void vStackPush( int v ) { aiStack[ ++iTop ] = v; }
static int iStackPop( void ) { return aiStack[ iTop-- ]; }

static int aiQ[ QUEUE_CAP ];
static int iQHead = 0, iQTail = 0, iQCount = 0;
static int iQEnqueue( int v )
{
if( iQCount == QUEUE_CAP ) { return -1; }
aiQ[ iQTail ] = v;
iQTail = ( iQTail + 1 ) % QUEUE_CAP;
iQCount++;
return 0;
}
static int iQDequeue( int * pv )
{
if( iQCount == 0 ) { return -1; }
*pv = aiQ[ iQHead ];
iQHead = ( iQHead + 1 ) % QUEUE_CAP;
iQCount--;
return 0;
}

int main( void )
{
for( int i = 1; i <= 5; i++ ) { vStackPush( i ); }
printf( "栈: push 1~5, iTop=%d\r\n", iTop );
printf( "栈: pop -> %d, pop -> %d, iTop=%d\r\n", iStackPop(), iStackPop(), iTop );

for( int i = 1; i <= 5; i++ ) { iQEnqueue( i * 10 ); }
int v;
iQDequeue( &v ); printf( "队列: 出队 %d, head=%d tail=%d count=%d\r\n", v, iQHead, iQTail, iQCount );
iQDequeue( &v ); printf( "队列: 出队 %d, head=%d tail=%d count=%d\r\n", v, iQHead, iQTail, iQCount );
iQEnqueue( 60 ); printf( "队列: 入队 60, head=%d tail=%d count=%d\r\n", iQHead, iQTail, iQCount );
iQEnqueue( 70 ); printf( "队列: 入队 70(满), head=%d tail=%d count=%d\r\n", iQHead, iQTail, iQCount );
return 0;
}

十一、实验 10:哈希表(ds10_hash.c)

预期现象:10 键 8 桶,桶 0/6/7 链长 2(碰撞),桶 3 为空,查找全部正确。

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

#define BUCKET_COUNT 8

typedef struct Entry
{
char pcKey[ 32 ];
int iValue;
struct Entry * pxNext;
} Entry;

static Entry * apxBuckets[ BUCKET_COUNT ];

static unsigned int ulHash( const char * pcKey )
{
unsigned int h = 5381;
while( *pcKey )
{
h = ( ( h << 5 ) + h ) + ( unsigned char ) *pcKey++;
}
return h % BUCKET_COUNT;
}

static void vPut( const char * pcKey, int iValue )
{
unsigned int b = ulHash( pcKey );
for( Entry * e = apxBuckets[ b ]; e != NULL; e = e->pxNext )
{
if( strcmp( e->pcKey, pcKey ) == 0 ) { e->iValue = iValue; return; }
}
Entry * e = ( Entry * ) malloc( sizeof( Entry ) );
strncpy( e->pcKey, pcKey, sizeof( e->pcKey ) - 1 );
e->pcKey[ sizeof( e->pcKey ) - 1 ] = 0;
e->iValue = iValue;
e->pxNext = apxBuckets[ b ];
apxBuckets[ b ] = e;
}

static int iGet( const char * pcKey, int * pv )
{
unsigned int b = ulHash( pcKey );
for( Entry * e = apxBuckets[ b ]; e != NULL; e = e->pxNext )
{
if( strcmp( e->pcKey, pcKey ) == 0 ) { *pv = e->iValue; return 1; }
}
return 0;
}

int main( void )
{
const char * apcKeys[] = { "apple", "banana", "grape", "cherry",
"pear", "peach", "melon", "kiwi", "lemon", "mango" };
for( int i = 0; i < 10; i++ )
{
vPut( apcKeys[ i ], ( i + 1 ) * 100 );
printf( "put %-7s -> 桶 %u\r\n", apcKeys[ i ], ulHash( apcKeys[ i ] ) );
}
for( int b = 0; b < BUCKET_COUNT; b++ )
{
printf( "桶 %d: ", b );
for( Entry * e = apxBuckets[ b ]; e != NULL; e = e->pxNext )
printf( "%s(%d) -> ", e->pcKey, e->iValue );
printf( "NULL\r\n" );
}
int v;
printf( "get(\"grape\") = %s%d\r\n", iGet( "grape", &v ) ? "" : "未找到", iGet( "grape", &v ) ? v : 0 );
printf( "get(\"nope\") = %s\r\n", iGet( "nope", &v ) ? "命中" : "未找到" );
return 0;
}

十二、实验 12:手写线程安全队列(ds12_tsqueue.c)

预期现象:手写队列(临界区保护)与内置 xQueue 各收发 500 条,全部按序零丢失。编译命令见第一节。完整源码较长(含内置对照组),此处收录手写队列核心;完整文件见仓库 ds-lab。

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
#include <stdio.h>
#include <stdlib.h>
#include "FreeRTOS.h"
#include "task.h"

#define TOTAL_ITEMS 500

typedef struct QNode
{
int iValue;
struct QNode * pxNext;
} QNode;

static QNode * pxQHead = NULL;
static QNode * pxQTail = NULL;
static volatile int iQCount = 0;

static void vTsPush( int iValue )
{
taskENTER_CRITICAL();
{
QNode * pxN = ( QNode * ) malloc( sizeof( QNode ) );
pxN->iValue = iValue;
pxN->pxNext = NULL;
if( pxQTail != NULL ) { pxQTail->pxNext = pxN; }
else { pxQHead = pxN; }
pxQTail = pxN;
iQCount++;
}
taskEXIT_CRITICAL();
}

static int iTsPop( int * piOut )
{
int iResult = -1;
taskENTER_CRITICAL();
{
if( pxQHead != NULL )
{
*piOut = pxQHead->iValue;
QNode * pxN = pxQHead;
pxQHead = pxQHead->pxNext;
if( pxQHead == NULL ) { pxQTail = NULL; }
iQCount--;
free( pxN );
iResult = 0;
}
}
taskEXIT_CRITICAL();
return iResult;
}
/* 生产者/消费者任务与内置 xQueue 对照组:完整代码见 ds12_tsqueue.c */

十三、收个尾

到这里,数据结构系列 13 篇全部完成:内存地图(13)→ 结构体(45)→ 线性结构(610)→ 内核实战与并发(1112),加上本篇代码附录。与本系列配合使用的还有隔壁的 FreeRTOS 学习笔记 12 篇——两边互相引用,一个讲内核,一个讲内核脚下的地基。

复现遇到问题先核对:gcc 是否在 PATH、工作目录是否正确、ds12 的内核路径是否匹配。祝折腾愉快!

参考资料