c - 尝试创建线程时 malloc 出错



大家好,我只发布创建probleam并与线程一起工作的代码核心。

#define HR_OFF h_r-1
pthread_t *threads = NULL;
int h_r = 1;
int foo(int handler)
{
    // if everything is empty alloc resources
    if (threads == NULL) {
        threads = (pthread_t*)malloc(sizeof(pthread_t));
        // stuff with other variables
        h_r++;
    }
    else {
        // stuff with other variables
        threads = (pthread_t*)realloc(threads, sizeof(pthread_t) * h_r);
        h_r++;
    }
    // stuff with other variables
    register unsigned int counter = 0;
    while (pthread_create(&threads[HR_OFF], NULL, (void*)&foo2, NULL) != 0) {
        if (counter == MAX_TRYING) {
            fprintf(stderr, "THREAD_ERROR_C occurs n");
            return THREAD_ERROR_C;
        }
    }
    return 0;
}
int foo2(void *data)
{
    // stuff with other variables
}

正如我们所看到的,foo函数创建新线程并重新分配内存以存储pthread_t。然后它尝试创建一个新线程,其中 pthread_create 为 NULL 作为 attr 和 arg,作为函数指针作为指向 foo2 的指针;

现在的问题是,当我执行代码时,当调用pthread_create时,内存分配出错,从而创建此错误消息:

  Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
      ../sysdeps/unix/sysv/linux/raise.c: File o directory non esistente.

如果使用 GDB 进行打印回溯

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff78513fa in __GI_abort () at abort.c:89
#2  0x00007ffff78939c8 in __malloc_assert (
    assertion=assertion@entry=0x7ffff7983088 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=file@entry=0x7ffff797f867 "malloc.c", line=line@entry=2406, function=function@entry=0x7ffff79838d0 <__func__.11275> "sysmalloc") at malloc.c:301
#3  0x00007ffff7895546 in sysmalloc (nb=nb@entry=288, av=0x7ffff7bb6b00 <main_arena>) at malloc.c:2403
#4  0x00007ffff789642d in _int_malloc (av=av@entry=0x7ffff7bb6b00 <main_arena>, bytes=bytes@entry=272) at malloc.c:3865
#5  0x00007ffff7898b4b in __libc_calloc (n=<optimized out>, elem_size=<optimized out>) at malloc.c:3274
#6  0x00007ffff7deaf42 in allocate_dtv (result=result@entry=0x7ffff781c700) at dl-tls.c:322
#7  0x00007ffff7deb8ce in __GI__dl_allocate_tls (mem=mem@entry=0x7ffff781c700) at dl-tls.c:539
#8  0x00007ffff7bc400c in allocate_stack (stack=<synthetic pointer>, pdp=<synthetic pointer>, attr=0x7fffffffe4b0) at allocatestack.c:580
---Type <return> to continue, or q <return> to quit---
#9  __pthread_create_2_1 (newthread=0x55555575b4c8, attr=<optimized out>, start_routine=0x5555555564fd <pthread_fetcher_function>, arg=0x0) at pthread_create.c:539

我怎么能解决这个问题,问题在哪里。

感谢大家的耐心和对不起我的英语

您的线程分配代码毫无意义,因为您只有 1 个线程句柄,并且threads[HR_OFF]访问它可能超出界限。投(void) * &foo2也是错误的,因为foo2有一个应有的正确签名。此外,在循环中重试失败的线程创建也不是一个好主意。请注意,此循环实际上是无穷无尽的,因为您从不递增counter 。在决定重试之前,至少应检查失败原因。

相关内容

  • 没有找到相关文章

最新更新