0

I have the following code which works fine for N=10 and C=25 but bombs with a segmentation fault if I use N=50 and C=25500

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

// create table
int *table;
table  = (int *) malloc(sizeof(int) * C+1 * N+1);
if(table == NULL){
  printf("[ERROR] : Fail to allocate memory.\n");
}

// initialize table
for(i =0; i < N-1; i++){
  for(j = 0; j < C-1; j++){
    //table[i*(C+1)+j]=0;
    *(table + (i*(C+1)+j))=1;
  }
}
printf("table made\n");
Dalupus
  • 1,100
  • 9
  • 19
  • 4
    So this works without a `main()`? – devnull Jan 28 '14 at 06:22
  • 2
    Make sure the math is correct inside of malloc, (you may mean (C+1)*(N+1)) – sudowoodo Jan 28 '14 at 06:28
  • where did you got the segmentation fault error? put printf statements inside for loop and try to find out at which location u got the segmentation fault..Because if malloc does not allocate any memory for large numbers we can find out in the `if(table == NULL)` condition. Pls try this – arunb2w Jan 28 '14 at 06:29
  • A good tool to help with this kind of problems is valgrind. – Johan Jan 28 '14 at 06:41

2 Answers2

3

I believe the amount of memory you are allocating is incorrect. You are allocating C*sizeof(int) + N + 1 and you want to be allocating (C+1)*(N+1)*sizeof(int)
You're just missing some parens -- http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

sudowoodo
  • 473
  • 4
  • 14
3

Assuming int = 4 so you allocate

4*50 + 1*25500 + 1 = 25701 bytes

In your loop you access (at the end):

i = 49
j = 25499

49*(25501)+25499 = 1275048(index)*4 = 5100192 (offset)

So what you need is:

 table  = malloc(sizeof(int) * (C+1) * (N+1));

Your loop didn't work for smaller values either, it just didn't crash. Writing outside allocated memory is undefined behaviour.

And as a sidenote, not related to your crash: Do I cast the result of malloc?

Community
  • 1
  • 1
Devolus
  • 21,661
  • 13
  • 66
  • 113