Reputation: 335
When compiling the program below, the terminal gives me the following message "double free or corruption (out)". I want to create a program that first calculates the sum of all the elements in an array, see x below. Then I want calculate the sum of all numbers in a memory block pointed to by a pointer, see y below. I believe that the problem lies in the assignment "y=x;"
int main(void)
{
double x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("The sum is %f\n", sum(x, 10));
double *y = malloc(sizeof(double)*10);
y = x;
printf("The sum is %f\n", sum(y, 10));
free(y);
return 0;
}
Upvotes: 0
Views: 441
Reputation: 53006
The assignment y = x
overwrites the malloc()
ed pointer and you end up free()
ing a stack variable1 which is undefined behavior. And also, the malloc()
ed pointer is never free()
ed.
From your code, it seems that you don't need malloc()
at all2. But if it's required then this might be what you need
double *y;
y = malloc(10 * sizeof(*y));
if (y == NULL)
return -1;
for (int i = 0 ; i < 10 ; ++i)
y[i] = i + 1;
printf("The sum is %f\n", sum(y, 10));
free(y);
1You actually free()
the address of x
.
2You could just call sum(x, 10)
.
Upvotes: 5
Reputation: 75062
You mustn't use free()
for what is not allocated via malloc()
, calloc()
or realloc()
(including functions that return pointers allocated via them, for example, strdup()
). If you do so, it means you invoke undefined behavior.
Quote from N1570 7.22.3.3 The free function:
If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
The y = x;
line causes memory leak because it will erase the pointer to the buffer allocated and assign the address of (first element of) x
to y
.
Upvotes: 1