【问题标题】:Allocating struct heap vs stack: Pthread_create分配结构堆与堆栈:Pthread_create
【发布时间】:2013-10-20 03:32:42
【问题描述】:

我正在尝试为 arg_struct 动态分配内存。如果我只是在堆栈上分配它,它可以正常工作,但不是动态的。它动态地在主函数中打印字符串,但是当它传递给线程函数时它不起作用。关于它为什么不起作用的任何想法?

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


struct arg_struct {
    int *arg1;
    char *str;
};

void *print_the_arguments(void *arguments)
{
    struct arg_struct *args = (struct arg_struct *)arguments;
    printf("The result is : %s\n",args->str);
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t some_thread;
    struct arg_struct *args = malloc(sizeof(struct arg_struct));
    //struct arg_struct args; // uncommenting this and args.str WORKS (prints to thread function)
    args->str = malloc(sizeof(char)*6);
    args->str = "hello";
    //args.str = "hello";
    printf("printing from main: %s\n", args->str); // Prints here but not in other function

    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
        printf("Uh-oh!\n");
        return -1;
    }

    return pthread_join(some_thread, NULL); /* Wait until thread is finished */

}

【问题讨论】:

  • 这个:args-&gt;str = malloc(sizeof(char)*5); args-&gt;str = "hello"; 分配五个字节(当您似乎想要 6 个时),然后当您将其他内容分配给 args-&gt;str 时立即丢失该内存。
  • 以后请在发帖前删除这些行号。

标签: c multithreading pthreads heap-memory stack-memory


【解决方案1】:

这个

29     if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {

应该是

29     if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)args) != 0) {

当您动态分配参数时。另外,我会建议

 25     args->str = strdup("hello");

并跳过malloc

这段代码:

 24     args->str = malloc(sizeof(char)*5);
 25     args->str = "hello";

导致内存泄漏,来自 malloc 的内存被泄漏。也许你的意思是

 24     args->str = malloc(sizeof(char)*5);
 25     strcpy(args->str, "hello");

但这也是不正确的。 5 应该是 6 来解释空字符 在字符串的末尾。 strdup()malloc 后跟strcpy 的一个很好的快捷方式。

【讨论】:

猜你喜欢
  • 2011-10-06
  • 1970-01-01
  • 2019-10-25
  • 2011-05-28
  • 2011-09-06
  • 2021-12-12
  • 2010-10-03
相关资源
最近更新 更多