AzmahQi
AzmahQi

Reputation: 378

C - Segmentation Fault (core dumbed) with malloc()

I have the following struct:

struct fibo_entry
{                          /* Definition of each table entry */
  int n;
  unsigned long long int lli;       /* 64-bit integer */
  char *str;
};

I am trying to print numbers and strings (number converted into a string) of X+1 number of Fibonacci passed by argument. And I am trying to create dynamically the space of str based in how many decimals I have on the actual number.

int main (int argc, char *argv[])
{
  int n;
  int i;
  struct fibo_entry *fibo_table;

  if (argc != 2)
    panic ("wrong parameters");

  n = atoi (argv[1]);
  if (n < 2)
    panic ("n too small");
  if (n > LIMIT)
    panic ("n too big");

    //Struct
    fibo_table = (struct fibo_entry*) malloc(sizeof(struct fibo_entry)*(n));
    //Fibonacci
    int var1 = 0;
    int var2 = 1;
    int aux = 0;
    for (i = 0; i<=n; i++)
    {
     fibo_table[i].lli = var1;
     if (var1 == 0){
        aux = 1;
     } else {
        aux = floor( log10( abs(var1)) + 1);
     }
     //When i use print no garbage chars...
     //printf("%d--> aux: %d var1: %d \n",i,aux,var1);
     //Generates the space of decimal we actually have on var1
     fibo_table[i].str = (char*)malloc(aux*sizeof(char));
     //Converts the number into string
     sprintf(fibo_table[i].str, "%llu", fibo_table[i].lli);
     aux = var1 + var2;
     var1 = var2;
     var2 = aux;
     fibo_table[i].n = i;
    }

  for (i = 0; i <= n; i++)
    {
      printf ("%d %llu %s\n", fibo_table[i].n, fibo_table[i].lli,
              fibo_table[i].str);
    }

  free_memory(fibo_table, n);

 return 0;
}

Here I am trying to liberate the memory.

void free_memory(struct fibo_entry *table, int size)
{
    int i;
    for (i = 0; i<size;i++){
        free(table[i].str);
    }
    free(table);
}

Output:

0 0 ��X�U
1 1 1
2 1 1
3 2 2
4 3 3
5 5 5
6 8 8
7 13 13
8 21 21
9 34 34
10 55 55
11 89 89
12 144 144
13 233 233
14 377 377
15 610 610
16 987 987
17 1597 1597
18 2584 2584
19 4181 4181
20 6765 6765
Segmentation fault (core dumbed)

The problem I have is I'm getting garbage chars on the str = 0, and I don't get why, when I do printf("%d--> aux: %d var1: %d \n",i,aux,var1); I don't get the garbage chars. Why is that? Also, I'm getting Segmentation fault because of free(). I've done some research but didn't found anything, I have already tried differents ways to free the memory:

free((*table)->str);
free(table[i]->str);
free(*(table+1)->str);
free(table[i].str);

Upvotes: 0

Views: 92

Answers (1)

William Pursell
William Pursell

Reputation: 212198

There certainly may be other issues, but since you've only allocated space for n structs, you cannot loop with for (i = 0; i<=n; i++).

You need to go one less than that with:

for (i = 0; i < n; i++)

Attempting to access fibo_table[n] is undefined behavior. The valid indices are 0 through n - 1.

Upvotes: 2

Related Questions