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"); 
4
  • 4
    So this works without a main()? Commented Jan 28, 2014 at 6:22
  • 2
    Make sure the math is correct inside of malloc, (you may mean (C+1)*(N+1)) Commented Jan 28, 2014 at 6: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 Commented Jan 28, 2014 at 6:29
  • A good tool to help with this kind of problems is valgrind. Commented Jan 28, 2014 at 6:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

ugg. I should have seen that. Thanks
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.