I have a program which calculates the “happy numbers” between an interval (definition). I have to write it in two ways, first one has to be sequential, second has to be parallel. The first program is done, and all I did was add an omp-specific line to the parallel version. The problem is, every time I run it it gives me this error: *** glibc detected *** ./p: double free or corruption (fasttop):
and then prints the “backtrace” and the “memory map”. I think it has something to do with the malloc and realloc I called, but no idea what. Could you help me with this?
#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;
}
The command I ran the code with was gcc main.c -o p -fopenmp
and then ./p 1 100 5
, but the error occurs at any number of threads (except 1 of course).