-2

I am creating a simple 2D long long int array dynamically in C, but freeing the array gives SIGTRAP ? I am really confused.The same code for int works perfectly fine. Why using it with long long int gives SIGTRAP ?

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

int main()
{
int i,j;
int n;
scanf("%d",&n);
long long int** ptr=(long long int**)calloc(n,sizeof(long long int*));
for(i=0;i<n;i++)
ptr[i]=(long long int*)calloc(n,sizeof(long long int));

for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
ptr[i-1][j-1]=i+j;

free(ptr[i]);
free(ptr);
return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

1

in ptr, you're allocating memory for n times sizeof (long long int *), but you're looping for a hardcoded value usning for(i=0;i<50;i++).

In case, n is less that 50, you're accessing out-of-bound memory by saying ptr[i]. Results in undefined behaviour.

That said, you should always check the return value of scanf() to ensure proper input, otherwise, as the code is currently written, in case scanf() fails, you'll face UB due to use of uninitialized local variable n.

Note: You need not and do not cast the return value of malloc() and family.


EDIT:

This time, the issues are

  1. accessing out-of-bound memory, in free(ptr[i]); without a reset of i value.

  2. Resulting Memory leak due to improper usage of index.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Here is your code with correct indentation for the structure.

int main()
{
    int i,j;
    int n;
    scanf("%d",&n);
    long long int** ptr=(long long int**)calloc(n,sizeof(long long int*));
    for(i=0;i<n;i++)
        ptr[i]=(long long int*)calloc(n,sizeof(long long int));

    for(i=1;i<=n;i++)
        for(j=i;j<=n;j++)
            ptr[i-1][j-1]=i+j;

    free(ptr[i]);
    free(ptr);
    return 0;
}

As you can see, the line free(ptr[i]); is only executed after the loop through all the is has exited. The loop exits when i == n + 1. ptr has been allocated with n blocks of memory indexed from 0 to n - 1. You are trying to free a garbage pointer that is after the end of the array.

I suspect what you really want is:

for (i = 0 ; i < n ; ++i)
{
    free(ptr[i]);
}

It's a matter of style, but I prefer to always put the braces in on loop and conditional bodies even if there is only one statement in the loop.

JeremyP
  • 84,577
  • 15
  • 123
  • 161