user3721298
user3721298

Reputation: 19

In C, memory allocating fails, why?

int x;
int komsuSayisi;//adjanceny matrix
int **arkadas;
int t;
int komsu[24][24];

scanf("%d",&t);
**arkadas = (int **)malloc( t*sizeof( int* )); //allocating rows
for(i=0; i<t; i++)
{
    x=0;
    arkadas[i] = (int *)malloc( t*sizeof(int) ); //allocating cow temporarily
    for(j=0; j<t; j++)
    {
        komsu[i][j]=fark(kelime[i],kelime[j]); //fark returns 1 or 0.
        //so i put those 1 ones to another matrix,arkadas
        if(komsu[i][j]==1){
            komsuSayisi++;
            arkadas[i][x]=j;
            x++;
        }
        arkadas[i] = (int *) realloc(arkadas[i], x);
        //real allocating here
    }

It gives error and shut downs.There is nothing wrong. What i want is adjanceny is too big to search so i will easily search the "1" ones with this matrix.

Upvotes: 1

Views: 104

Answers (2)

vmp
vmp

Reputation: 2420

I see

 komsuSayisi++;

You didn't paste the whole code but probably thats what is crashing your program... I don't see any initializing previous to that increment....

this plus the deferentiation posted on the other answer

Upvotes: 1

simonc
simonc

Reputation: 42195

**arkadas = (int **)malloc( t*sizeof( int* ));

should be

arkadas = malloc( t*sizeof( int* ));

**arkadas dereferences an uninitialised pointer, resulting in you trying to write to an unpredictable address. You don't own the memory at this address so it isn't safe to try and write to it.

The second form assigns the address of an array of pointers to the local variable arkadas; this is what need to do.

Later in your program

if(komsu[i][j]==1){
    komsuSayisi++;
    arkadas[i][x]=j;
    x++;
}
arkadas[i] = (int *) realloc(arkadas[i], x);

code inside the if condition attempts to write to arkadas[i] before you allocate it. This also invokes undefined behaviour and will likely crash. You can avoid the crash by removing the line arkadas[i][x]=j; and swapping your realloc call for malloc (you need the address of a previous allocation before you can call realloc)

if(komsu[i][j]==1){
    komsuSayisi++;
    x++;
}
arkadas[i] = malloc(x*sizeof(int));

Upvotes: 5

Related Questions