MST
星途 面试题库

面试题:C语言Linux线程创建传递结构体参数的注意事项

在Linux C编程中,创建线程并向线程函数传递一个自定义结构体参数。请说明传递过程中可能遇到的内存管理问题及如何避免,同时给出完整代码实现。
44.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

可能遇到的内存管理问题及避免方法

  1. 栈内存释放问题:如果结构体变量定义在线程创建函数的栈上,当线程创建函数返回时,栈内存会被释放,导致传递给线程函数的结构体指针指向无效内存。避免方法是使用堆内存来分配结构体。
  2. 内存泄漏:如果在堆上分配了结构体内存,在线程函数结束后没有释放,会导致内存泄漏。可以在线程函数内部使用atexit函数注册释放内存的函数,或者在线程创建函数中等待线程结束后手动释放内存。

完整代码实现

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 自定义结构体
typedef struct {
    int value1;
    char value2;
} CustomStruct;

// 线程函数
void* threadFunction(void* arg) {
    CustomStruct* data = (CustomStruct*)arg;
    printf("Thread received value1: %d, value2: %c\n", data->value1, data->value2);
    free(data); // 释放堆内存
    pthread_exit(NULL);
}

int main() {
    pthread_t thread;
    CustomStruct* data = (CustomStruct*)malloc(sizeof(CustomStruct));
    if (data == NULL) {
        perror("malloc");
        return 1;
    }
    data->value1 = 42;
    data->value2 = 'A';

    int result = pthread_create(&thread, NULL, threadFunction, (void*)data);
    if (result != 0) {
        perror("pthread_create");
        free(data);
        return 1;
    }

    pthread_join(thread, NULL);
    return 0;
}