【发布时间】:2021-12-28 11:56:52
【问题描述】:
我有一个程序可以计算间隔 (definition) 之间的“快乐数字”。我必须以两种方式编写它,第一种必须是顺序的,第二种必须是并行的。第一个程序完成了,我所做的只是在并行版本中添加了一个特定于 omp 的行。问题是,每次运行它都会给我这个错误:*** glibc detected *** ./p: double free or corruption (fasttop): 然后打印“回溯”和“内存映射”。我认为这与我调用的 malloc 和 realloc 有关,但不知道是什么。你能帮我解决这个问题吗?
#include <stdio.h>
#include <omp.h>
#include <sys/time.h>
#include <math.h>
#define LLI long long int
int length(LLI n) {
int len = 0;
while (n != 0) {
n /= 10;
len++;
}
return len;
}
void breakdown(int *a, LLI n, int len) {
int i;
for (i = len - 1; i >= 0; i--) {
a[i] = n % 10;
n /= 10;
}
}
int calculate(int *a, int* len) {
int i, sum = 0;
for (i = 0; i < *len; i++) {
sum += pow(a[i], 2);
}
if (sum < 10) {
*len = 1;
} else {
*len = length(sum);
breakdown(a, sum, *len);
}
return sum;
}
int calculateHappy(int *a, int len) {
int sum;
do {
sum = calculate(a, &len);
} while (len != 1);
if (sum == 1) {
return 1;
}
return 0;
}
int main(int argc, const char* argv[]) {
if (argc != 4) {
printf("man no good bro i ned 3 parameter\np: interval left border\nq: interval right border\nthreadNr: think bro think what could it be\n");
exit(0);
}
LLI p, q, i, *result;
int *a, len, j, happyNr = 0, threadNr;
p = atoll(argv[1]);
q = atoll(argv[2]);
threadNr = atoi(argv[3]);
result = (LLI*) malloc (1 * sizeof(LLI));
if (p >= q) {
printf("man no good bro p < q man\n");
exit(0);
}
struct timeval start, stop;
gettimeofday(&start, NULL);
#pragma omp parallel for num_threads(threadNr) shared (happyNr, result)
for (i = p; i < q; i++) {
printf("%d. thread: i am at %d\n", omp_get_thread_num(), i);
len = length(i);
a = (int*) malloc (len * sizeof(int));
breakdown(a, i, len);
if (calculateHappy(a, len)) {
happyNr++;
result = (LLI*) realloc (result, happyNr * sizeof(LLI));
result[happyNr - 1] = i;
}
}
gettimeofday(&stop, NULL);
printf("The program took %d seconds/%d microseconds to run\n", stop.tv_sec - start.tv_sec, stop.tv_usec - start.tv_usec);
FILE *f = fopen("output.txt", "w");
if (happyNr != 0) {
fprintf(f, "The happy numbers are: \n");
for (i = 0; i < happyNr; i++) {
fprintf(f, "%lli ", result[i]);
}
fprintf(f,"\n");
} else {
fprintf(f, "In the interval [%lli, %lli] there are no happy numbers.\n", p, q);
}
free(result);
return 0;
}
我运行代码的命令是gcc main.c -o p -fopenmp,然后是./p 1 100 5,但错误发生在任意数量的线程(当然除了1)。
【问题讨论】:
-
在
printf("%d. thread: i am at %d\n", omp_get_thread_num(), i);中应该是...i am at %lld...和printf("The program took %d seconds/%d microseconds to run\n", stop.tv_sec - start.tv_sec, stop.tv_usec - start.tv_usec);应该是program took %ld...首先修复这些,错误的 printf 说明符会导致未定义的行为。顺便说一句,彩色错误消息;) -
我刚才评论了那部分。仍然不起作用,大多数时候我得到
Aborted (core dumped)或分段错误 -
如果这有帮助,我收到的其他
glibc detected消息是realloc(): invalid next size和malloc(): invalid next size -
尝试在循环内声明
a。int *a = (int*) malloc (len * sizeof *a);当然删除之前的声明。 -
是的,它们并没有消失,肯定有问题,不幸的是我现在没有时间,尝试使用 valgrind,彻底调试也可能会有所帮助
标签: c linux parallel-processing openmp glibc