0

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

}
4

1 に答える 1

4

これ

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()ための適切なショートカットです。mallocstrcpy

于 2013-10-11T23:13:47.633 に答える