我有一个短程序,在运行几次(例如:在一个循环中运行10次)后,会在RPi4上造成分段错误。我正在使用Raspbian /Linux 10 (buster)和默认gcc编译器(sudo apt安装构建-基本)。
gcc --version
gcc (Raspbian 8.3.0-6+rpi1) 8.3.0你认为这是gcc编译器的问题吗?也许我错过了一些RPi4的特殊设置。我用它来构建:
gcc threads.c -o threads -l pthread输出有时(并非总是)如下所示:
...
in thread_dummy, loop: 003
Segmentation fault守则如下:
#include <stdio.h> /* for puts() */
#include <unistd.h> /* for sleep() */
#include <stdlib.h> /* for EXIT_SUCCESS */
#include <pthread.h>
#define PTR_SIZE (0xFFFFFF)
#define PTR_CNT (10)
void* thread_dummy(void* param)
{
void* ptr = malloc(PTR_SIZE);
//fprintf(stderr, "thread num: %03i, stack: %08X, heap: %08X - %08X\n", (int)param, (unsigned int)¶m, (unsigned int)ptr, (unsigned int)((unsigned char*)ptr + PTR_SIZE));
fprintf(stderr, "in thread_dummy, loop: %03i\n", (int)param);
sleep(1);
free(ptr);
pthread_detach(pthread_self());
return NULL;
}
int main(void)
{
void* ptrs[PTR_CNT];
pthread_t threads[PTR_CNT];
for(int i=0; i<PTR_CNT; ++i)
{
ptrs[i] = malloc(PTR_SIZE);
//fprintf(stderr, "main num: %03i, stack: %08X, heap: %08X - %08X\n", i, (unsigned int)&ptrs, (unsigned int)ptrs[i], (unsigned int)((unsigned char*)ptrs[i] + PTR_SIZE));
fprintf(stderr, "in main, loop: %03i\n", i);
}
fprintf(stderr, "-----------------------------------------------------------\n");
for(int i=0; i<PTR_CNT; ++i)
pthread_create(&threads[i], 0, thread_dummy, (void*)i);
for(int i=0; i<PTR_CNT; ++i)
pthread_join(threads[i], NULL);
for(int i=0; i<PTR_CNT; ++i)
free(ptrs[i]);
return EXIT_SUCCESS;
}更新:我也和新gcc一起测试过,但问题仍然存在.
gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/arm-linux-gnueabihf/11.1.0/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: ../configure --enable-languages=c,c++,fortran --with-cpu=cortex-a72 --with-fpu=neon-fp-armv8 --with-float=hard --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 11.1.0 (GCC)发布于 2021-05-14 07:17:14
pthread_create像malloc,pthread_detach 或 pthread_join像free。你基本上是在做一些类似于“双自由”的事情--你分离一个线程,同时加入它。要么断开线程,要么加入线程。
您可以从pthread_join中删除main。但是,您应该在逻辑上从线程中删除pthread_detach(...),这实际上是无用的,因为线程在线程结束后就会立即终止。
https://stackoverflow.com/questions/67501298
复制相似问题