Why does a semaphore in a Linux C language program cause SIGABRT Aborted?

Viewed 42

My development environment is CentOS 7.9-x86_64 and the compiler is using gcc11.

[root@dev src]# uname -a
Linux dev 3.10.0-1160.24.1.el7.x86_64 #1 SMP Thu Apr 8 19:51:47 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
[root@dev src]# 
[root@dev src]# 
[root@dev src]# cat /etc/redhat-release 
CentOS Linux release 7.9.2009 (Core)
[root@dev src]# 
[root@dev src]# 
[root@dev src]# gcc --version
gcc (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9)
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@dev src]#

Below is my code snippet:

  1. This is a header file that defines a structure EuclidCommand, and this structure contains a semaphore.
#include <semaphore.h>

typedef struct euclid_command
{
    char *bytes;
    char *result;
    sem_t sem;
} EuclidCommand;
  1. The following is the program logic part.
/**
* Allocate a piece of memory for the structure object EuclidCommand, and allocate 
* an additional 4 bytes as additional information for this structure object.
*/
int hidden = 4;
void *obj_head = malloc(hidden + sizeof(EuclidCommand));
memset(obj_head, 0, hidden + sizeof(EuclidCommand));
EuclidCommand *task = obj_head + hidden;
task->bytes = buf;

sem_init(&(task->sem), 0, 0);

/**
* Submit the task object to another thread for processing, that thread will increment 
* the value of the semaphore by 1 after execution is complete.
*/
submit_command(task);

sem_wait(&(task->sem));
sem_destroy(&(task->sem));

// do something

The above code can be executed correctly. Next, I made a small change, I changed the number of bytes of that additional memory from 4 to 2.

/**
* Allocate a piece of memory for the structure object EuclidCommand, and allocate 
* an additional 2 bytes as additional information for this structure object.
*/
int hidden = 2;
void *obj_head = malloc(hidden + sizeof(EuclidCommand));
memset(obj_head, 0, hidden + sizeof(EuclidCommand));
EuclidCommand *task = obj_head + hidden;

Execute the program again after recompiling the code. When the 'sem_wait(&(task->sem));' line of code is executed, the program fails. Use gdb to view the program stack at that time as shown in the following figure: enter image description here

I guess the cause of this problem is related to byte alignment, but I am not sure of the real cause of this problem. I hope to meet friends who are familiar with Linux C language development to help me answer.
thank you very much

0 Answers
Related