Advanced C Programming Techniques and Best Practices - Complete Edition Table of Contents
Macro Definitions and Preprocessing Techniques
Advanced Memory Management Techniques
Function Pointers and Callback Mechanisms
Data Structure Design
Concurrency and Multithreading
Error Handling and Exception Mechanisms
Performance Optimization Techniques
Debugging and Testing Techniques
Cross-Platform Programming
Secure Programming Practices
Comprehensive Demonstration Examples
Macro Definitions and Preprocessing Techniques
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #if defined(_WIN32) || defined(_WIN64) #define PLATFORM_WINDOWS #elif defined(__linux__) #define PLATFORM_LINUX #elif defined(__APPLE__) #define PLATFORM_MACOS #endif #if defined(__GNUC__) #define COMPILER_GCC #elif defined(_MSC_VER) #define COMPILER_MSVC #endif #if __STDC_VERSION__ >= 201112L #define C11_SUPPORTED #endif
2. Advanced Macro Techniques 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 // Stringification and concatenation#define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define CONCAT(a, b) a##b // Get array size#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) // container_of macro (get container pointer from member pointer)#define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ ((type *)(__mptr - offsetof(type , member))); }) // Min/Max values #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) // Variable swap (without temporary variable)#define SWAP(a, b) do { typeof(a) temp = a; a = b; b = temp; } while(0) // Compile-time assertion #define STATIC_ASSERT(condition, message) \ typedef char static_assertion_##message[ ;(condition) ? 1 : -1 ] // Variadic macros#define DEBUG_PRINT(fmt, ...) \ fprintf(stderr, "[DEBUG] %s:%d: " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
3. Modern C Language Features 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #define generic_max(a, b) _Generic((a), \ int : max_int, \ float : max_float, \ double : max_double \ )(a, b) _Static_assert(sizeof (int ) >= 4 , "int must be at least 4 bytes" ); _Thread_local int thread_var;
Advanced Memory Management Techniques
1. Memory Pool Design 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 typedef struct { void *memory; size_t size; size_t used; size_t block_size; } memory_pool_t ;memory_pool_t * create_pool (size_t size, size_t block_size) { memory_pool_t *pool = malloc (sizeof (memory_pool_t )); pool->memory = malloc (size); pool->size = size; pool->used = 0 ; pool->block_size = block_size; return pool; }void * pool_alloc (memory_pool_t *pool, size_t size) { if (pool->used + size > pool->size) return NULL ; void *ptr = (char *)pool->memory + pool->used; pool->used += size; return ptr; }
2. Smart Pointer Simulation 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 #include <stdatomic.h> typedef struct { void *ptr; void (*deleter)(void *); atomic_int *ref_count; } smart_ptr_t ;smart_ptr_t make_smart_ptr (void *ptr, void (*deleter)(void *)) { smart_ptr_t sp = {ptr, deleter, malloc (sizeof (atomic_int))}; atomic_init (sp.ref_count, 1 ); return sp; }smart_ptr_t smart_ptr_copy (smart_ptr_t sp) { atomic_fetch_add (sp.ref_count, 1 ); return sp; }void smart_ptr_free (smart_ptr_t *sp) { if (atomic_fetch_sub (sp->ref_count, 1 ) == 1 ) { sp->deleter (sp->ptr); free (sp->ref_count); } }
3. Memory Alignment 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 _Alignas(16 ) char aligned_buffer[ ;256 ];#define ALIGN_UP(x, align) (((x) + (align) - 1) & ~((align) - 1)) #define IS_ALIGNED(x, align) (((x) & ((align) - 1)) == 0) void * aligned_malloc (size_t size, size_t alignment) { void *ptr = malloc (size + alignment - 1 + sizeof (void *)); if (!ptr) return NULL ; void **aligned_ptr = (void **)(((uintptr_t )ptr + sizeof (void *) + alignment - 1 ) & ~(alignment - 1 )); aligned_ptr[ ;-1 ] = ptr; return aligned_ptr; }
Function Pointers and Callback Mechanisms
1. Object-Oriented Style Programming 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 typedef struct { void (*destroy)(void *self ); void (*print)(void *self ); int (*compare)(void *self , void *other); } vtable_t;typedef struct { vtable_t *vtable; } object_t;#define CALL_METHOD(obj, method, ...) \ ((obj)->vtable->method((obj), ##__VA_ARGS__))
2. State Machine Implementation 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 typedef enum { STATE_IDLE, STATE_RUNNING, STATE_PAUSED, STATE_STOPPED } state_t;typedef struct { state_t current_state; int (*handlers[ ;4 ])(void *context , int event ); } state_machine_t;int handle_idle(void *context , int event ) { switch (event ) { case EVENT_START: return STATE_RUNNING; default : return STATE_IDLE; } }
3. Plugin System Design 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 typedef struct { const char *name; int version; int (*init)(void ); void (*cleanup)(void ); void * (*create_instance)(void ); } plugin_interface_t;#ifdef _WIN32 #include <windows.h> #define LOAD_PLUGIN(name) LoadLibrary(name) #define GET_SYMBOL(handle, name) GetProcAddress(handle, name) #else #include <dlfcn.h> #define LOAD_PLUGIN(name) dlopen(name, RTLD_LAZY) #define GET_SYMBOL(handle, name) dlsym(handle, name) #endif
Data Structure Design
1. Linked List Implementation 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 typedef struct list_node { void *data; struct list_node *next; struct list_node *prev; } list_node_t ;typedef struct { list_node_t head; size_t size; void (*destructor)(void *); } list_t ;void list_insert_after (list_t *list, list_node_t *node, void *data) { list_node_t *new_node = malloc (sizeof (list_node_t )); new_node->data = data; new_node->next = node->next; new_node->prev = node; if (node->next) node->next->prev = new_node; node->next = new_node; list->size++; }
2. Hash Table Implementation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 typedef struct hash_entry { char *key; void *value; struct hash_entry *next; } hash_entry_t ;typedef struct { hash_entry_t **buckets; size_t bucket_count; size_t size; unsigned int (*hash_func) (const char *) ; } hash_table_t ;unsigned int djb2_hash (const char *str) { unsigned int hash = 5381 ; int c; while ((c = *str++)) hash = ((hash << 5 ) + hash) + c; return hash; }
3. Ring Buffer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 typedef struct { char *buffer; size_t size; size_t read_pos; size_t write_pos; int full; } ring_buffer_t ;int ring_buffer_write (ring_buffer_t *rb, const char *data, size_t len) { size_t available = rb->size - ring_buffer_size (rb); if (len > available) return -1 ; for (size_t i = 0 ; i < len; i++) { rb->buffer[ ;rb->write_pos] = data[ ;i]; rb->write_pos = (rb->write_pos + 1 ) % rb->size; if (rb->write_pos == rb->read_pos) rb->full = 1 ; } return len; }
Concurrency and Multithreading
1. Thread-Safe Data Structures 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 #include <pthread.h> typedef struct { int value; pthread_mutex_t mutex; pthread_cond_t cond; } thread_safe_counter_t ;void counter_increment (thread_safe_counter_t *counter) { pthread_mutex_lock (&counter->mutex); counter->value++; pthread_cond_signal (&counter->cond); pthread_mutex_unlock (&counter->mutex); }int counter_wait_for (thread_safe_counter_t *counter, int target) { pthread_mutex_lock (&counter->mutex); while (counter->value < target) { pthread_cond_wait (&counter->cond, &counter->mutex); } pthread_mutex_unlock (&counter->mutex); return counter->value; }
2. Read-Write Lock Implementation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 typedef struct { pthread_mutex_t mutex; pthread_cond_t read_cond; pthread_cond_t write_cond; int readers; int writers; int waiting_writers; } rwlock_t ;void rwlock_rdlock (rwlock_t *rwlock) { pthread_mutex_lock (&rwlock->mutex); while (rwlock->writers > 0 || rwlock->waiting_writers > 0 ) { pthread_cond_wait (&rwlock->read_cond, &rwlock->mutex); } rwlock->readers++; pthread_mutex_unlock (&rwlock->mutex); }
3. Lock-Free Programming 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <stdatomic.h> typedef struct { atomic_int value; } atomic_counter_t ;void atomic_counter_increment (atomic_counter_t *counter) { atomic_fetch_add (&counter->value, 1 ); }int atomic_counter_get (atomic_counter_t *counter) { return atomic_load (&counter->value); }
Error Handling and Exception Mechanisms
1. Error Code System 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 typedef enum { ERROR_SUCCESS = 0 , ERROR_INVALID_PARAM = -1 , ERROR_OUT_OF_MEMORY = -2 , ERROR_FILE_NOT_FOUND = -3 , ERROR_PERMISSION_DENIED = -4 } error_code_t ;#define RETURN_ON_ERROR(expr) do { \ error_code_t err = (expr); \ if (err != ERROR_SUCCESS) return err; \ } while(0) typedef struct { error_code_t code; const char *message; const char *file; int line; } error_context_t ;
2. Exception Simulation Mechanism 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 typedef struct { jmp_buf jump_buffer; int error_code; const char *error_message; } exception_context_t;static __thread exception_context_t *current_exception = NULL; do { \ exception_context_t __exception_ctx; \ __exception_ctx.error_code = 0 ; \ if (setjmp(__exception_ctx.jump_buffer) == 0 ) { \ current_exception = &__exception_ctx; } else { \ error_var = current_exception->error_code; } \ current_exception = NULL; \ } while (0 ); do { \ if (current_exception) { \ current_exception->error_code = code; \ current_exception->error_message = message; \ longjmp(current_exception->jump_buffer, 1 ); \ } \ } while (0 )
3. Resource Management (RAII) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 typedef struct { void *resource; void (*cleanup)(void *); } raii_guard_t; type name = init; \ raii_guard_t __guard_ __attribute__((cleanup(raii_cleanup))) raii_guard_t *__raii_static void raii_cleanup(raii_guard_t **guard) { if ((*guard)->resource && (*guard)->cleanup) { (*guard) -> cleanup((*guard)->resource) ; } }
Performance Optimization Techniques
1. Cache-Friendly Data Structures 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 struct __attribute__((packed)) packed_struct { char a; int b; short c; };#define CACHE_LINE_SIZE 64 struct __attribute__((aligned(CACHE_LINE_SIZE))) cache_aligned_struct { int data[16]; };
2. Branch Prediction Optimization 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #define likely (x) __builtin_expect (!!(x), 1 )#define unlikely (x) __builtin_expect (!!(x), 0 ) void optimized_function (int *array, size_t size) { if (unlikely(size == 0 )) return; for (size_t i = 0 ; likely(i < size); i ++) { process_element (array[ ;i]); } }
3. Inline Assembly Optimization 1 2 3 4 5 6 7 8 9 10 11 12 13 14 static inline uint64_t rdtsc (void ) { uint32_t lo, hi; __asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi)); return ((uint64_t )hi << 32 ) | lo; }#define MEMORY_BARRIER() __asm__ __volatile__("" ::: "memory" )
4. SIMD Optimization 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #ifdef __SSE2__ #include <emmintrin.h> void vector_add (float *a, float *b, float *result, size_t n) { size_t i = 0 ; for (; i + 4 <= n; i += 4 ) { __m128 va = _mm_load_ps(&a[ ;i]); __m128 vb = _mm_load_ps(&b[ ;i]); __m128 vr = _mm_add_ps(va, vb); _mm_store_ps(&result[ ;i], vr); } for (; i < n; i++) { result[ ;i] = a[ ;i] + b[ ;i]; } }#endif
Debugging and Testing Techniques
1. Debug Macros 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 #ifdef DEBUG #define DBG_PRINT(fmt, ...) \ fprintf(stderr, "[DEBUG] %s:%d: " fmt "\n" , __FILE__ , __LINE__ , ##__VA_ARGS__) #define ASSERT(condition) \ do { \ if (!(condition)) { \ fprintf(stderr, "Assertion failed: %s at %s:%d\n" , \ #condition, __FILE__, __LINE__); \ abort() } \ } while (0 )#else #define DBG_PRINT(fmt, ...) do {} while(0 ) #define ASSERT(condition) do {} while(0 ) #endif #define TIME_IT(code, result_var) \ do { \ clock_t start = clock() code result_var = ((double )(clock() - start)) / CLOCKS_PER_SEC } while (0 )
2. Unit Testing Framework 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 typedef struct { const char *name; void (*test_func)(void ); int passed; int failed; } test_case_t; static void test_ static test_case_t test_case_ static void test_ do { \ if ((expected) != (actual)) { \ fprintf(stderr, "Assertion failed: %s != %s at %s:%d\n" , \ current_test->failed++; \ } else { \ current_test->passed++; \ } \ } while (0 )
3. Memory Leak Detection 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 #ifdef DEBUG_MEMORY static size_t total_allocated = 0 ;static size_t allocation_count = 0 ;void * debug_malloc (size_t size, const char *file, int line) { void *ptr = malloc (size + sizeof (size_t )); if (ptr) { *(size_t *)ptr = size; total_allocated += size; allocation_count++; printf ("ALLOC: %zu bytes at %s:%d\n" , size, file, line); return (char *)ptr + sizeof (size_t ); } return NULL ; }void debug_free (void *ptr, const char *file, int line) { if (ptr) { size_t *size_ptr = (size_t *)((char *)ptr - sizeof (size_t )); total_allocated -= *size_ptr; allocation_count--; printf ("FREE: %zu bytes at %s:%d\n" , *size_ptr, file, line); free (size_ptr); } }#define malloc(size) debug_malloc(size, __FILE__, __LINE__) #define free(ptr) debug_free(ptr, __FILE__, __LINE__) #endif
Cross-Platform Programming
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 #ifdef _WIN32 #include <windows.h> typedef HANDLE thread_t ; typedef CRITICAL_SECTION mutex_t ; #define THREAD_CREATE(thread, func, arg) \ (thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, NULL)) #define THREAD_JOIN(thread) WaitForSingleObject(thread, INFINITE) #define MUTEX_INIT(mutex) InitializeCriticalSection(mutex) #define MUTEX_LOCK(mutex) EnterCriticalSection(mutex) #define MUTEX_UNLOCK(mutex) LeaveCriticalSection(mutex) #else #include <pthread.h> typedef pthread_t thread_t ; typedef pthread_mutex_t mutex_t ; #define THREAD_CREATE(thread, func, arg) pthread_create(&thread, NULL, func, arg) #define THREAD_JOIN(thread) pthread_join(thread, NULL) #define MUTEX_INIT(mutex) pthread_mutex_init(mutex, NULL) #define MUTEX_LOCK(mutex) pthread_mutex_lock(mutex) #define MUTEX_UNLOCK(mutex) pthread_mutex_unlock(mutex) #endif
2. File Path Handling 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 #ifdef _WIN32 #define PATH_SEPARATOR '\\' #define PATH_SEPARATOR_STR "\\" #else #define PATH_SEPARATOR '/' #define PATH_SEPARATOR_STR "/" #endif char * join_path (const char *dir, const char *file) { size_t dir_len = strlen (dir); size_t file_len = strlen (file); char *result = malloc (dir_len + file_len + 2 ); strcpy (result, dir); if (dir[ ;dir_len - 1 ] != PATH_SEPARATOR) { strcat (result, PATH_SEPARATOR_STR); } strcat (result, file); return result; }
3. Endianness Handling 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define IS_BIG_ENDIAN 1 #else #define IS_BIG_ENDIAN 0 #endif static inline uint32_t swap_endian_32 (uint32_t val) { return ((val & 0x000000FF ) << 24 ) | ((val & 0x0000FF00 ) << 8 ) | ((val & 0x00FF0000 ) >> 8 ) | ((val & 0xFF000000 ) >> 24 ); }#define hton32(x) (IS_BIG_ENDIAN ? (x) : swap_endian_32(x)) #define ntoh32(x) hton32(x)
Secure Programming Practices
1. Buffer Overflow Protection 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 size_t safe_strncpy (char *dest, size_t dest_size, const char *src, size_t count) { if (dest_size == 0 ) return 0 ; size_t copy_len = (count < dest_size - 1 ) ? count : dest_size - 1 ; memcpy (dest, src, copy_len); dest[ ;copy_len] = '\0' ; return copy_len; }#define SAFE_PRINTF(buffer, size, format, ...) \ do { \ int __result = snprintf(buffer, size, format, ##__VA_ARGS__); \ if (__result < 0 || (size_t)__result > = size) { \ \ buffer[size - 1] = '\0' ; \ } \ } while(0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 static inline int safe_add (int a, int b, int *result ) { if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) { return -1 ; } *result = a + b; return 0 ; }#define VALIDATE_PTR(ptr) \ do { \ if (!(ptr)) { \ return ERROR_INVALID_PARAM; \ } \ } while (0 )
3. Secure Random Numbers 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 #include <time.h> #include <stdlib.h> #ifdef __linux__ #include <sys/random.h> int secure_random_bytes (void *buf, size_t len) { return getrandom (buf, len, 0 ) == (ssize_t )len ? 0 : -1 ; }#else static unsigned long long rand_state = 1 ; void srand64 (unsigned long long seed) { rand_state = seed; } unsigned long long rand64 (void ) { rand_state = rand_state * 6364136223846793005ULL + 1 ; return rand_state; }#endif
Comprehensive Demonstration Examples
Event-Driven Architecture Demo 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 typedef enum { EVENT_NONE = 0 , EVENT_TIMER, EVENT_NETWORK, EVENT_USER, EVENT_SYSTEM } event_type_t ;typedef struct { event_type_t type; uint64_t timestamp; void *data; size_t data_size; } event_t ;typedef int (*event_handler_t ) (event_t *event, void *context) ;typedef struct { event_type_t type; event_handler_t handler; void *context; int priority; } event_listener_t ;typedef struct { event_listener_t *listeners; size_t listener_count; size_t listener_capacity; event_t *event_queue; size_t queue_head; size_t queue_tail; size_t queue_size; size_t queue_capacity; int running; pthread_mutex_t mutex; pthread_cond_t cond; } event_loop_t ;
Lock-Free Queue Implementation 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 #include <stdatomic.h> typedef struct queue_node { void *data; _Atomic(struct queue_node*) next; } queue_node_t ;typedef struct { _Atomic(queue_node_t *) head; _Atomic(queue_node_t *) tail; atomic_size_t size; } lockfree_queue_t ;
Cache-Friendly Data Structures 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 /** * Cache-friendly data structure implementation * Optimizes memory layout to improve cache hit rates */ /** * Cache line size definition */ /** * Cache alignment macro */ /** * SoA (Structure of Arrays) vector structure * Separates related data storage to improve cache efficiency */ typedef struct { float *x; // X-coordinate array float *y; // Y-coordinate array float *z; // Z-coordinate array int *id; // ID array size_t capacity; // Capacity size_t size; // Current size char padding& } soa_vector_t; // &
Secure String Operations Library 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <string.h> #include <stdio.h> #include <stdarg.h> typedef struct { char *data; size_t length; size_t capacity; int is_secure; } secure_string_t ;
Comprehensive Demo Function 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 void demo_event_driven_architecture () { printf ("=== Event-Driven Architecture Demo ===\n" ); event_loop_t *loop = event_loop_create (100 ); if (!loop) { printf ("Failed to create event loop\n" ); return ; } event_loop_add_listener (loop, EVENT_TIMER, timer_handler, NULL , 0 ); event_loop_add_listener (loop, EVENT_NETWORK, network_handler, NULL , 0 ); event_loop_add_listener (loop, EVENT_USER, user_handler, NULL , 0 ); pthread_t loop_thread; pthread_create (&loop_thread, NULL , (void *(*)(void *))event_loop_run, loop); for (int i = 0 ; i < 5 ; i++) { event_t event = {0 }; event.timestamp = time (NULL ); switch (i % 3 ) { case 0 : event.type = EVENT_TIMER; printf ("Posting timer event %d\n" , i); break ; case 1 : { event.type = EVENT_NETWORK; const char *msg = "Hello Network!" ; event.data = strdup (msg); event.data_size = strlen (msg); printf ("Posting network event %d\n" , i); break ; } case 2 : event.type = EVENT_USER; event.data = malloc (sizeof (int )); *(int *)event.data = i; event.data_size = sizeof (int ); printf ("Posting user event %d\n" , i); break ; } event_loop_post (loop, &event); sleep (1 ); } sleep (2 ); event_loop_stop (loop); pthread_join (loop_thread, NULL ); event_loop_destroy (loop); printf ("=== Demo Complete ===\n\n" ); }
Appendix: Best Practices Summary
Coding Standards Naming Conventions: Use clear names, avoid abbreviations
Comment Style: Use Doxygen-style comments
Error Handling: Always check return values
Memory Management: Follow RAII principles
Thread Safety: Clearly identify thread-safe functions
Measure Before Optimizing: Use profiling tools
Algorithm First: Choose appropriate data structures and algorithms
Avoid Premature Optimization: Maintain code readability
Cache-Friendly: Consider data locality
Compiler Optimization: Use compiler optimization flags appropriately
Secure Coding Principles Input Validation: Never trust external input
Bounds Checking: Prevent buffer overflows
Principle of Least Privilege: Use minimum necessary privileges
Safe Functions: Use secure string functions
Code Reviews: Conduct regular security code reviews
This comprehensive guide to advanced C programming techniques covers all important aspects from basic macros to complex concurrent programming, providing rich code examples and best practices to help developers write high-quality, high-performance, and secure C code.
相关阅读