Hello ,

why am I taking :

*** glibc detected *** ./run: double free or corruption (out)

#include <stdio.h>
#include <stdlib.h>

void func1(int **A )

    *A = (int*) malloc( 2 * sizeof(int));

    for (int i = 0; i < 10; i++){
       (*A)[ i ] = i;
       //printf("\nA = %d\n", (*A)[ i ]);    


int main( int argc, const char* argv[] ){

    int *A;   

    func1( &A );

    for (int i = 0; i < 10; i++)
        printf("\nA = %d\n", A[ i ]);    

   free ( A );

return 0;


when I free A ?

Recommended Answers

All 8 Replies

Unless I'm reading this wrongly (because you have written this in a somewhat odd style with more layers of pointer redirection than you need), you are allocating enough space for 2 int values, and then trying to store ten int values in that space, so you're writing over eight int values' worth of memory that you shouldn't be.

When you trash memory like this, funny things happen. What result do you get if, on line 8, you allocate enough memory for all the int values you are trying to store?

Oh!! I totally forgot that!I left it to 2 by mistake!
Now its ok , thanks!

But why do you state that

more layer of pointer redirection that you need

I need to use double pointer in order to take the result back (it's a void function)

If you're doing it for the fun of it, fine of course, but otherwise I'd use a straight array instead of a function at all, or if you must have a function, since it's handling the memory allocation, it might as well pass back the pointer it creates in doing so rather than assign its value to one you passed in through a pointer-to-a-pointer.

Hello and thanks for the answer.

I am sorry that I can't understand exactly what you are saying.

I don't know any other way to deal with passing pointer values between functions.

If you can write the function in another way in order to understand , I 'll appreciate.


This is bad:

 *A = (int*) malloc( 2 * sizeof(int));

 for (int i = 0; i < 10; i++){
    (*A)[ i ] = i;

You allocated room for two integers in the array, but are setting 10 items.

Additionally, in main(), you need to initialize A to 0 (NULL), and test it for null before iterating over it and deleting it after calling func1.

As a result, you have seriously munged the stack, and the error you got may not be exactly what happened, you should have had a SEGFAULT core dump...

Yes , as I told before , I missed that , ok.

But I didn't understand what "Moschops" said in the last post.


I think that Moschops means something like this:

int* func1( size_t cnt )
    int* pA = (int*) malloc( cnt * sizeof(int));
    for (int i = 0; i < cnt; i++)
        pA[ i ] = i;
    return pA;

Oh , ok !

But I prefer the void way.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.