Note that there are some explanatory texts on larger screens.

plurals
  1. POSegmentation Fault in C, possibly on medium/large dynamically allocated arrays
    text
    copied!<p><strong>NOTE:</strong> I have looked at other segmentation fault postings, and the ones that relate closely to my problem are when large arrays are created on the stack eventually causing an overflow. However, as you can see from the code below, I am allocating on the heap and still encountering this problem. </p> <p>I have used both Valgrind and gdb to debug this, and they tell me the following: There's an "Invalid read of size 4 ... numberDivisors" or segmentation fault occurring in the function code below. The odd thing is, this works for all numbers up to 49141 after it loops through the numbers of interest when it will either throw the error or segfault. <strong>This is only when it is in a loop.</strong> When I put in a single large number without looping, it will report back the number of divisors without erring out or segfault-ing. Can anyone see what the problem is in the code below? Thanks!</p> <pre><code>int numberDivisors(int n) { int lim = (int)floor(sqrt((double)n)); int *primes = (int*)calloc(n, sizeof(int)); int *divisors = (int*)calloc(n, sizeof(int)); int i, j, ctr; ctr = 0; if(primes &amp;&amp; divisors) { for(i = 0; i &lt; n; i++) { primes[i] = 1; divisors[i] = 0; } for(i = 2; i &lt; lim; i++) { if(primes[i]) { for(j = i; i * j &lt; n; j++) { primes[i * j] = 0; } } } for(i = 2; i &lt; n; i++) { if(primes[i]) { if(n % i == 0) divisors[i] = 1; for(j = i; i * j &lt; n; j++) { // int result = n % (i * j); assert(i * j &lt; n); //Added at lsk's request. i * j passes the test. //if(result == 0) { if(n % (i * j) == 0) { if(!divisors[i * j]) { divisors[i * j] = 1; } } } } } for(i = 2; i &lt; n; i++) { if(divisors[i]) ctr++; } ctr += 2; } else { printf("Allocation failed."); } free(primes); free(divisors); return ctr; } </code></pre> <p><strong>UPDATE</strong> I changed all the int's in the function to unsigned long (just to see that it would work), and it's running just fine now. However, Umer is right - I have to rethink the algorithm because it takes longer than is necessary, but that is another question all together. Thank you for the assistance SO community!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload