使用结构作为线程的参数调用pthread_create时出现的额外字符

ecbunoof  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(127)

我观察到,当我将一个结构体作为参数传递给线程时,该结构体的字符串成员在线程内部比线程长几个字符。
所以基本上,在main中,s-dev是12个字符长。当s作为参数传递给pthread_create时,s-〉dev变成了14个字符长。什么会破坏字符串?有人能解释一下原因吗?
代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

void *rtu_worker(void *ptr);

typedef struct mb_serial_dev_config
{
    char parity;
    char *dev;
    uint8_t databits;
    uint8_t stopbits;
    uint32_t baudrate;
} mb_serial_dev_config_t;

int main(int argc, char *argv[])
{
    int r_th = 0;
    pthread_t rtu_thread;
    mb_serial_dev_config_t *s = (mb_serial_dev_config_t *)malloc(sizeof(mb_serial_dev_config_t));

    //com1 config
    char *serial_device = "/dev/ttyUSB1";
    int32_t baud = 9600;
    char parity = 'N';
    int32_t databits = 8;
    int32_t stopbits = 1;

    s->dev = (char *)malloc(strlen(serial_device));
    strcpy(s->dev,serial_device);
    s->parity = parity;
    s->baudrate = baud;
    s->databits = databits;
    s->stopbits = stopbits;

    printf("%s(%d)\n",s->dev, strlen(s->dev));
    r_th = pthread_create(&rtu_thread, NULL, rtu_worker, s);
    printf("Waiting on threads ...");
    pthread_join(rtu_thread, NULL);
    printf("exiting the main application ...\n");
}

void *rtu_worker(void *ptr)
{
    int count = 0;
    mb_serial_dev_config_t *d = (mb_serial_dev_config_t *)ptr;

    printf("%s(%d)\n",d->dev, strlen(d->dev));

    //print the device name character by character
    while(count < strlen(d->dev)){
        printf("(%d)  %c (%d)\n", count, (d->dev)[count], (d->dev)[count]);
        count++;
    }
}
6rqinv9w

6rqinv9w1#

您忘记为字符串的终止零字符'\0'保留内存

s->dev = (char *)malloc(strlen(serial_device) + 1);
strcpy(s->dev,serial_device);

注意,函数strlen的返回类型是size_t,因此在调用printf时,需要使用转换说明符zu,而不是d,如

printf("%s(%zu)\n",s->dev, strlen(s->dev));

函数rtu_worker也不返回任何东西,尽管它的返回类型不是void

void *rtu_worker(void *ptr)

相关问题