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

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(20);
    strcpy(a,"hello world");
}

int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
                                        //value so to use that we need double pointer
    printf("b is %s.\n",b);

    return 0;
}

using -O0 and -O1 to compile and run:

[root c++]#gcc -g -O0 -o pthread pthread.c -lpthread
[root c++]#
[root c++]#
[root c++]#./pthread
b is hello world.
[root c++]#
[root c++]#
[root c++]#gcc -g -O1 -o pthread pthread.c -lpthread
[root c++]#
[root c++]#./pthread
b is .

why does this happen? source code from pthread_join() and pthread_exit() Since I am not familiar with assembly language, can anyone help me to analyze the reason ? online assembly

Nik O'Lai
  • 3,586
  • 1
  • 15
  • 17
J.Doe
  • 319
  • 1
  • 8

1 Answers1

4

If you don't return anything inside your thread_function is an UB, with -O0 the compiler automatically solving this problem. In fact, your function is:

thread_function:
      push    rbp
      mov     rbp, rsp
      sub     rsp, 32
      mov     QWORD PTR [rbp-24], rdi
      mov     edi, 20
      call    malloc
      mov     QWORD PTR [rbp-8], rax
      mov     rax, QWORD PTR [rbp-8]
      movabs  rdx, 8031924123371070824
      mov     QWORD PTR [rax], rdx
      mov     DWORD PTR [rax+8], 6581362
      nop
      leave
      ret

However, when you compile with -O1, your function is:

thread_function:
        ret

Also, if you don't know Assembly, you can understand that this procedure just returns without doing anything but if you add return a; at the end of your thread_function, your function becomes:

thread_function:
      sub     rsp, 8
      mov     edi, 20
      call    malloc
      movabs  rdx, 8031924123371070824
      mov     QWORD PTR [rax], rdx
      mov     DWORD PTR [rax+8], 6581362
      add     rsp, 8
      ret

Now if you execute the program, the output is correct.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Holeryn
  • 387
  • 1
  • 4
  • 11