带有包含结构的字符串的多线程

问题描述 投票:0回答:1

我无法弄清楚为什么在使用

pthread_join()
线程结束后字符串会损坏。

这里是C代码(不是C++)和背景:

    我正在调试一个大型程序,以解决多线程中的段错误。为了找到原因,我主要从“Create a thread from IBM”处的代码中编写了代码片段,具有类似的“struct”,其中有一个字符串,

    char*
    ,成员。当线程结束时,字符串被损坏。

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // strcpy


typedef struct data {
  char *ret;
  int i;
} data;


void *thread(data* data_shared) {

  printf("thread() entered with argument '%s' and %d \n",
    data_shared->ret, data_shared->i);

  strcpy(data_shared->ret, "This is a test");
  data_shared->i += 1;

  pthread_exit(data_shared);
}


// ----- ----- ----- -----
main() {
  pthread_t thid;
  data* data_shared;

  data_shared = malloc(sizeof(data));
  data_shared->i = 1;
  data_shared->ret = malloc(sizeof(char)); // like pointer of pointer
  strcpy(data_shared->ret, "thread 1");

  if (pthread_create(&thid, NULL, thread, data_shared) != 0) {
    perror("pthread_create() error");
    exit(1);
  }

  if (pthread_join(thid, data_shared) != 0) {
    perror("pthread_join() error");
    exit(3);
  }

  printf("thread exited with '%s' and %d \n",
    data_shared->ret, data_shared->i);

  // free(data_shared->ret);
  free(data_shared);
}

输出为:

thread() entered with argument 'thread 1' and 1
thread exited with '▒ধ`' and 2

  我希望“这是测试”而不是“▒ধ`”。

我需要修复代码中的哪些位置?

c string multithreading struct
1个回答
0
投票

尝试

data_shared->ret = malloc(strlen("This is a test") + 1);
。为较长的字符串分配内存,并为空终止符加一。

© www.soinside.com 2019 - 2024. All rights reserved.