2013-10-11 85 views
0

我想爲arg_struct動態分配內存。如果我只是在堆棧上分配它,它會正常工作,但不是動態的。動態地,它在主函數中打印字符串,但是當它傳遞給線程函數時,它不起作用。任何想法爲什麼它不起作用?分配struct堆棧:Pthread_create

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

} 
+0

這個:'args-> str = malloc(sizeof(char)* 5); args-> str =「hello」;'分配五個字節(當你想要6個時),然後當你爲'args-> str'分配別的東西時,立即丟失那個內存。 –

+0

將來,請在發佈前刪除這些行號。 – hauzer

回答

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) { 

當你動態分配ARGS。此外,我建議

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的好捷徑。

+0

+ 1,在''void *'中強制轉換,'print_the_arguments'前面的'&'和OP代碼中的'sizeof(char)'也是不必要的。 –

+0

可能不需要但不必要?該代碼來自另一個stackoverflow頁面;我只是稍微改動了一下。此外,此頁面已經轉換爲void *。 https://computing.llnl.gov/tutorials/pthreads/這個網站也使用sizeof(char):http://stackoverflow.com/questions/8600181/allocate-memory-and-save-string-in-c –