Advanced C Programming Techniques and Best Practices – Complete Edition


Advanced C Programming Techniques and Best Practices – Complete Edition

Table of Contents

  1. Macro Definitions and Preprocessing Techniques
  2. Advanced Memory Management Techniques
  3. Function Pointers and Callback Mechanisms
  4. Data Structure Design
  5. Concurrency and Multithreading
  6. Error Handling and Exception Mechanisms
  7. Performance Optimization Techniques
  8. Debugging and Testing Techniques
  9. Cross-Platform Programming
  10. Secure Programming Practices
  11. Comprehensive Demonstration Examples

Macro Definitions and Preprocessing Techniques

1. Conditional Compilation and Platform Detection

/**
 * Platform and compiler detection
 * Used for conditional compilation and cross-platform compatibility
 */
#if defined(_WIN32) || defined(_WIN64)
    #define PLATFORM_WINDOWS
#elif defined(__linux__)
    #define PLATFORM_LINUX
#elif defined(__APPLE__)
    #define PLATFORM_MACOS
#endif

// Compiler detection
#if defined(__GNUC__)
    #define COMPILER_GCC
#elif defined(_MSC_VER)
    #define COMPILER_MSVC
#endif

// Version detection
#if __STDC_VERSION__ >= 201112L
    #define C11_SUPPORTED
#endif

2. Advanced Macro Techniques

/**
 * Advanced macro collection
 * Provides type-safe and convenient macro utilities
 */

// 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

/**
 * C11 modern features
 * Leverage new standards to improve code quality
 */

// Generic selection
#define generic_max(a, b) _Generic((a), \
    int: max_int, \
    float: max_float, \
    double: max_double \
)(a, b)

// Static assertion (C11)
_Static_assert(sizeof(int) >= 4, "int must be at least 4 bytes");

// Thread-local storage (C11)
_Thread_local int thread_var;

Advanced Memory Management Techniques

1. Memory Pool Design

/**
 * Memory pool implementation
 * Provides efficient memory allocation and recycling
 */
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

/**
 * Smart pointer simulation system
 * Implements reference-counted automatic memory management
 */

#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

/**
 * Memory alignment utilities
 * Ensures proper alignment of data structures in memory
 */

// C11 alignment
_Alignas(16) char aligned_buffer[256];

// Manual alignment
#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

/**
 * Virtual function table simulation
 * Implements object-oriented programming in C
 */

// Virtual function table simulation
typedef struct {
    void (*destroy)(void *self);
    void (*print)(void *self);
    int (*compare)(void *self, void *other);
} vtable_t;

typedef struct {
    vtable_t *vtable;
    // Concrete data
} object_t;

// Polymorphic invocation
#define CALL_METHOD(obj, method, ...) \
    ((obj)->vtable->method((obj), ##__VA_ARGS__))

2. State Machine Implementation

/**
 * State machine implementation
 * Provides flexible state management mechanism
 */

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

/**
 * Plugin system design
 * Supports dynamic loading and functionality extension
 */

typedef struct {
    const char *name;
    int version;
    int (*init)(void);
    void (*cleanup)(void);
    void* (*create_instance)(void);
} plugin_interface_t;

// Dynamic plugin loading
#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

/**
 * Doubly linked list implementation
 * Provides efficient insertion and deletion operations
 */

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;

// Doubly linked list operations
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

/**
 * Hash table implementation
 * Provides fast key-value storage and retrieval
 */

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

/**
 * Ring buffer implementation
 * Suitable for producer-consumer patterns
 */

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

/**
 * Thread-safe counter
 * Provides atomic operations and conditional waiting
 */

#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

/**
 * Read-write lock implementation
 * Supports multiple readers/single writer concurrency control
 */

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

/**
 * Lock-free programming tools
 * Implements high-performance concurrency using atomic operations
 */

#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

/**
 * Error code system
 * Provides structured error handling mechanism
 */

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)

// Context-aware error handling
typedef struct {
    error_code_t code;
    const char *message;
    const char *file;
    int line;
} error_context_t;

2. Exception Simulation Mechanism

/**
 * Exception simulation mechanism
 * Implements exception handling using setjmp/longjmp
 */

#include <setjmp.h>

typedef struct {
    jmp_buf jump_buffer;
    int error_code;
    const char *error_message;
} exception_context_t;

static __thread exception_context_t *current_exception = NULL;

#define TRY \
    do { \
        exception_context_t __exception_ctx; \
        __exception_ctx.error_code = 0; \
        if (setjmp(__exception_ctx.jump_buffer) == 0) { \
            current_exception = &__exception_ctx;

#define CATCH(error_var) \
        } else { \
            error_var = current_exception->error_code;

#define END_TRY \
        } \
        current_exception = NULL; \
    } while(0);

#define THROW(code, message) \
    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)

/**
 * RAII resource management
 * Ensures automatic resource cleanup
 */

typedef struct {
    void *resource;
    void (*cleanup)(void*);
} raii_guard_t;

#define RAII_VAR(type, name, init, cleanup_func) \
    type name = init; \
    raii_guard_t __guard_##name = {&name, (void(*)(void*))cleanup_func}; \
    __attribute__((cleanup(raii_cleanup))) raii_guard_t *__raii_##name = &__guard_##name;

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

/**
 * Cache-friendly data structures
 * Optimizes memory layout for better cache hit rates
 */

// Struct packing optimization
struct __attribute__((packed)) packed_struct {
    char a;
    int b;
    short c;
};

// Cache line alignment
#define CACHE_LINE_SIZE 64
struct __attribute__((aligned(CACHE_LINE_SIZE))) cache_aligned_struct {
    int data[16];
};

2. Branch Prediction Optimization

/**
 * Branch prediction optimization
 * Uses compiler hints to improve execution efficiency
 */

// Static branch prediction
#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

/**
 * Inline assembly optimization
 * Directly uses CPU instructions for performance gains
 */

// Read Time-Stamp Counter
static inline uint64_t rdtsc(void) {
    uint32_t lo, hi;
    __asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi));
    return ((uint64_t)hi << 32) | lo;
}

// Memory barrier
#define MEMORY_BARRIER() __asm__ __volatile__("" ::: "memory")

4. SIMD Optimization

/**
 * SIMD optimization
 * Leverages vector instructions for parallel data processing
 */

#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);
    }
    // Process remaining elements
    for (; i < n; i++) {
        result[i] = a[i] + b[i];
    }
}
#endif

Debugging and Testing Techniques

1. Debug Macros

/**
 * Debugging utility macros
 * Provides convenient debugging and profiling capabilities
 */

#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

// Performance timing
#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

/**
 * Unit testing framework
 * Provides structured testing support
 */

typedef struct {
    const char *name;
    void (*test_func)(void);
    int passed;
    int failed;
} test_case_t;

#define TEST_CASE(name) \
    static void test_##name(void); \
    static test_case_t test_case_##name = {#name, test_##name, 0, 0}; \
    static void test_##name(void)

#define ASSERT_EQ(expected, actual) \
    do { \
        if ((expected) != (actual)) { \
            fprintf(stderr, "Assertion failed: %s != %s at %s:%d\n", \
                    #expected, #actual, __FILE__, __LINE__); \
            current_test->failed++; \
        } else { \
            current_test->passed++; \
        } \
    } while(0)

3. Memory Leak Detection

/**
 * Memory leak detection
 * Tracks memory allocations and deallocations
 */

#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. Platform Abstraction Layer

/**
 * Platform abstraction layer
 * Provides unified cross-platform interfaces
 */

// Thread abstraction
#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

/**
 * File path handling
 * Provides cross-platform path operations
 */

#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

/**
 * Endianness handling
 * Ensures data correctness during network transmission
 */

// Network byte order conversion
#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

/**
 * Buffer overflow protection
 * Provides safe string manipulation functions
 */

// Safe string operations
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;
}

// Formatted string safety checks
#define SAFE_PRINTF(buffer, size, format, ...) \
    do { \
        int __result = snprintf(buffer, size, format, ##__VA_ARGS__); \
        if (__result < 0 || (size_t)__result >= size) { \
            /* Handle overflow */ \
            buffer[size - 1] = '\0'; \
        } \
    } while(0)

2. Input Validation

/**
 * Input validation
 * Prevents security issues caused by malicious input
 */

// Integer overflow check
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; // Overflow
    }
    *result = a + b;
    return 0;
}

// Pointer validation
#define VALIDATE_PTR(ptr) \
    do { \
        if (!(ptr)) { \
            return ERROR_INVALID_PARAM; \
        } \
    } while(0)

3. Secure Random Numbers

/**
 * Secure random number generation
 * Provides cryptographically secure random numbers
 */

#include <time.h>
#include <stdlib.h>

// Cryptographically secure random numbers (requires platform support)
#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
    // Simple pseudo-random number generator
    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

/**
 * Event-Driven Architecture - Event Type Definitions
 * Used for building flexible event handling systems
 */
typedef enum {
    EVENT_NONE = 0,
    EVENT_TIMER,
    EVENT_NETWORK,
    EVENT_USER,
    EVENT_SYSTEM
} event_type_t;

/**
 * Event structure
 * Contains event type, timestamp, and user data
 */
typedef struct {
    event_type_t type;
    uint64_t timestamp;
    void *data;
    size_t data_size;
} event_t;

/**
 * Event handler function pointer type
 * @param event Event pointer
 * @param context User context
 * @return Processing result
 */
typedef int (*event_handler_t)(event_t *event, void *context);

/**
 * Event listener structure
 * Stores event type and corresponding handler
 */
typedef struct {
    event_type_t type;
    event_handler_t handler;
    void *context;
    int priority;  // Processing priority
} event_listener_t;

/**
 * Event loop structure
 * Manages event queue and listeners
 */
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;

// [Implementation code continues...]

Lock-Free Queue Implementation

/**
 * Lock-free queue implementation
 * Implements thread-safe lock-free queue using CAS operations
 */

#include <stdatomic.h>

/**
 * Queue node structure
 */
typedef struct queue_node {
    void *data;
    _Atomic(struct queue_node*) next;
} queue_node_t;

/**
 * Lock-free queue structure
 */
typedef struct {
    _Atomic(queue_node_t*) head;
    _Atomic(queue_node_t*) tail;
    atomic_size_t size;
} lockfree_queue_t;

// [Implementation code continues...]

Cache-Friendly Data Structures

/**
 * Cache-friendly data structure implementation
 * Optimizes memory layout to improve cache hit rates
 */

/**
 * Cache line size definition
 */
#define CACHE_LINE_SIZE 64

/**
 * Cache alignment macro
 */
#define CACHE_ALIGNED __attribute__((aligned(CACHE_LINE_SIZE)))

/**
 * 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[CACHE_LINE_SIZE - sizeof(size_t)*2 - sizeof(char*)*4]; // Padding to cache line boundary
} soa_vector_t;

// [Implementation code continues...]

Secure String Operations Library

/**
 * Secure string operations library
 * Provides buffer-overflow-safe string functions
 */

#include <string.h>
#include <stdio.h>
#include <stdarg.h>

/**
 * Secure string structure
 * Contains length information to prevent overflows
 */
typedef struct {
    char *data;
    size_t length;
    size_t capacity;
    int is_secure;  // Whether security checks are enabled
} secure_string_t;

// [Implementation code continues...]

Comprehensive Demo Function

/**
 * Event-Driven Architecture Demo Example
 */
void demo_event_driven_architecture() {
    printf("=== Event-Driven Architecture Demo ===\n");
    
    // Create event loop
    event_loop_t *loop = event_loop_create(100);
    if (!loop) {
        printf("Failed to create event loop\n");
        return;
    }
    
    // Add event listeners
    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);
    
    // Start event loop thread
    pthread_t loop_thread;
    pthread_create(&loop_thread, NULL, (void*(*)(void*))event_loop_run, loop);
    
    // Post some test events
    for (int i = 0; i < 5; i++) {
        event_t event = {0};
        event.timestamp = time(NULL);
        
        // Post different event types
        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);
    }
    
    // Cleanup event data
    sleep(2);
    
    // Stop and destroy event loop
    event_loop_stop(loop);
    pthread_join(loop_thread, NULL);
    event_loop_destroy(loop);
    
    printf("=== Demo Complete ===\n\n");
}

// [Other demo functions continue...]

Appendix: Best Practices Summary

Coding Standards

  1. ​Naming Conventions​​: Use clear names, avoid abbreviations
  2. ​Comment Style​​: Use Doxygen-style comments
  3. ​Error Handling​​: Always check return values
  4. ​Memory Management​​: Follow RAII principles
  5. ​Thread Safety​​: Clearly identify thread-safe functions

Performance Optimization Principles

  1. ​Measure Before Optimizing​​: Use profiling tools
  2. ​Algorithm First​​: Choose appropriate data structures and algorithms
  3. ​Avoid Premature Optimization​​: Maintain code readability
  4. ​Cache-Friendly​​: Consider data locality
  5. ​Compiler Optimization​​: Use compiler optimization flags appropriately

Secure Coding Principles

  1. ​Input Validation​​: Never trust external input
  2. ​Bounds Checking​​: Prevent buffer overflows
  3. ​Principle of Least Privilege​​: Use minimum necessary privileges
  4. ​Safe Functions​​: Use secure string functions
  5. ​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.

此条目发表在未分类分类目录。将固定链接加入收藏夹。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注