Runtime error while accessing an array for some specific cases - c

I have the following code to generate prime factors of a number. It is working fine with all the numbers except some. The error I am getting in these numbers is runtime error which is at line 5 and line 10, when trying to access 'factors' array.
and also why is it not giving error when accessing 'factors' array in line 15 and 18.
*This is working perfectly for numbers both greater and lesser than 48598496894, just not for 48598496894.
void getfactors(unsigned long long n){
unsigned long long *factors,i=0,k=0;
//array to store prime factors//
factors=(unsigned long long *)malloc(n*sizeof(unsigned long long));
//getting 2's which are factors of the number//
while(n%2==0){
factors[k++]=2; //line 5
n=n/2;
}
//getting other prime factors of the number//
for(i=3;i<=sqrt(n);i=i+2){
while(n%i==0){
factors[k++]=i; //line 10
n=n/i;
}
}
//last prime factor of number//
if(n>2)
factors[k++]=n; //line 15
printf("%d\n\n",k);
//printing all factors//
for(i=0;i<k;i++)
printf("%llu\n",factors[i]); //line 18
}
int main()
{
getfactors(48598496894);
return 0;
}

You should be checking that factors is not NULL after the malloc in case the allocation fails. You also need to call free to release the memory that you allocated once you're done with it. It would also help if you commented your code to explain your intended behaviour.
To solve your problem I'd recommend checking your array indexing whilst debugging. It might be easier if you used a smaller input value to begin with until you know that your algorithm works.
One other point is whether you need the factors array at all? If the purpose of the function is to print the prime factors, couldn't you just print them as you find them?
Edit
I think #BLUEPIXY has hinted at the issue in the comments. The input argument to malloc is a size_t. On my PC size_t is a 32 bit value. If that's the case on your platform then the size of the block of memory you're trying to allocate is too big. Check if (n*sizeof(unsigned long long)) > SIZE_MAX. As I mentioned earlier, could you just print the factors as you find them and do away with the array?

Related

Abort trap: 6 (Calculating a long number factorial)

I am following the following function to calculate factorials of big numbers link, and I would like to understand a bit more why some things are happening...
#include<stdio.h>
#define MAX 10000
void factorialof(int);
void multiply(int);
int length = 0;
int fact[MAX];
int main(){
int num;
int i;
printf("Enter any integer number : ");
scanf("%d",&num);
fact[0]=1;
factorialof(num);
printf("Factorial is : ");
for(i=length;i>=0;i--){
printf("%d",fact[i]);
}
return 0;
}
void factorialof(int num){
int i;
for(i=2;i<=num;i++){
multiply(i);
}
}
void multiply(int num){
long i,r=0;
int arr[MAX];
for(i=0;i<=length;i++){
arr[i]=fact[i];
}
for(i=0;i<=length;i++){
fact[i] = (arr[i]*num + r)%10;
r = (arr[i]*num + r)/10;
//printf("%d ",r);
}
if(r!=0){
while(r!=0){
fact[i]=r%10;
r= r/10;
i++;
}
}
length = i-1;
}
My questions are:
What is the real meaning of the MAX constant? What does it mean if it's bigger or smaller?
I have found out that if I have a MAX = 10000 (as in the example), I can calculate up to 3250! If I try with 3251! I get a 'Abort trap: 6' message. Why is that number? Where does it come from?
Which would be the difference if I compile this code for a 32-bit machine with the flag -m32? Would it run he same as in 64-bit?
Thanks!
As Scott Hunter points out, MAX is the maximum number of elements in the fact and arr arrays, which means it's the maximum number of digits that can occur in the result before the program runs out of space.
Note that the code only uses MAX in its array declarations. Nowhere does it use MAX to determine whether or not it's trying to read from or write to memory beyond the end of those arrays. This is a Bad Thing™. Your "Abort trap: 6" error is almost certainly occurring because trying to compute 3251! is doing exactly that: using a too-large index with arr and fact.
To see the number of digits required for a given factorial, you can increase MAX (say, to 20,000) and replace the existing printf calls in main with something like this:
printf("Factorial requires %d digits.\n", length + 1);
Note that I use length + 1 because length isn't the number of digits by itself: rather, it's the index of the array position in fact that contains the most-significant digit of the result. If I try to compute 3251!, the output is:
Factorial requires 10008 digits.
This is eight digits more than you have available in fact with the default MAX value of 10,000. Once the program logic goes beyond the allocated space in the array, its behavior is undefined. You happen to be seeing the error "Abort trap: 6."
Interestingly, here's the output when I try to compute 3250!:
Factorial requires 10005 digits.
That's still too many for the program to behave reliably when MAX is set to 10,000, so the fact that your program calculates 3250! successfully might be surprising, but that's the nature of undefined behavior: maybe your program will produce the correct result, maybe it will crash, maybe it will become self-aware and launch its missiles against the targets in Russia (because it knows that the Russian counterattack will eliminate its enemies over here). Coding like this is not a good idea. If your program requires more space than it has available in order to complete the calculation, it should stop and display an appropriate error message rather than trying to continue what it's doing.
MAX is the number of elements in fact and arr; trying to access an element with an index >= MAX would be bad.
Error messages are often specific to the environment you are using, which you have provided no details for.
They are not the same, but the differences (for example, the size of pointers) should not affect this code in any discernible way.

Why i'm getting runtime error in ideone and codechef compiler and not in my terminal?

I have just started competitive programming in SPOJ.I'm confused from sometime why i'm getting runtime error in ideone.The question is:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
My program:
#include <stdio.h>
int main(void)
{
int t,i,reverse,same;
scanf("%d",&t); //t is no. of test cases
int num[t]; //num[t] is array of t elements
for(i=0;i<t;i++)
scanf("%d",&num[i]);
i=0; //since i will be equal to t therefore i is assigned to 0.
while(t--)
{
if(num[i]<=1000000)
{
while(num[i]++)
{
reverse=0;
same=num[i];
while(same>0)
{
reverse=reverse*10;
reverse=reverse+same%10;
same=same/10;
}
if(reverse==num[i])
printf("%d",reverse);
printf("\n");
if(reverse==num[i])
break;
}
}
i++;
}
return 0;
}
I don't know where i'm wrong.I'm sorry i'm asking this question may this question is asked by someone before.I tried to find the result but could not get the answer.Thankyou in advance and sorry for my bad english.
The question doesn't say that the number will be less than 1000000. It says that the number has less than 1 million digits. A number with a million digits looks like this
591875018734106743196734198673419067843196874398674319687431986743918674319867431986743198674319876341987643198764319876341987643198764319876431987643198763419876431987643198764319876139876...
You can't use scanf to read a number that has a million digits, and you can't store that number in an int.
The most likely reason for your error to occur is some memory fault. Keep in mind that online judges/compilers limit your available memory and if you try to allocate/use more memory than available, you get a runtime error. This also happens on your machine, but usually you have a lot more memory available for your program than in the case of online judges.
In your case, you could reduce the memory usage of your program by changing the data type of the num array from int to something like short or even char.

sum of even terms in the fibonacci series less than 4 million

////Even Fibonacci numbers
int i=2;
int sum_of_Even=0;
int fib_array[]={};
fib_array[0]=1;
fib_array[1]=1;
while (fib_array[i]<4000000)
{
fib_array[i]=fib_array[i-1]+fib_array[i-2];
if ((fib_array[i]%2) == 0)
{
sum_of_Even+=fib_array[i];
}
i++;
}
printf("sum of Even terms in the fib sequence = %i\n", sum_of_Even);
On the terminal, the output is 3.. Help!
Program looks good...but somehow gives an output of 3 (which is pretty wrong)..
Open to suggestions on how to fix this..
Thanks..
The problem is likely here: (Anyway this is a big problem even if it is not the problem.)
int fib_array[]={};
The space allocated for your array in memory will not grow dynamically as you appear to expect. You need to manage the memory for it somehow. Right now you are overflowing this array substantially and it is amazing that this program does not crash or segfault.
Edit: Moreover, every time your while loop checks its condition for whether to run again, it accesses an entry in your array which has not been initialized! Note:
On the first run, it checks whether fib_array[2] < 4000000, which you are about to set in the body of the loop!
On the second run, it checks whether fib_array[3] < 4000000, which you are about to set in the body of the loop!
Etc.
Edit 2: Since (amazingly many) people have been posting that you need to use a 64 bit integer and that this is the source of your problems, I'd like to make the clarifying remark that the answer is in the 5 million range, so a 32 bit integer is plenty big.
fib_array[i] is not initialized when you access it in the while() test. Try changing your while loop to while(true) and using if (fib_array[i]<4000000) break; on the line after you set fib_array[i].
Also, your sum_of_Even is going to need to be a 64 bit integer, so you'll need:
#include <stdint.h>
and then declare it as uint64_t.
Another problem is you aren't declaring how large your fib_array should be, so no actual memory is being allocated to it. Try int fib_array[MAXSIZE]; where MAXSIZE is your calculation for how many entries it will need.
Suggestions on how to fix:
And mindful of #Andrey comment:
"For the record: this is a Project Euler question, and people are strongly discouraged from posting solutions to these online."
Use an array of long long fib_array[3]. To generate Fibonacci numbers only the previous 2 are used to generate the 3rd. After generating a Fibonacci number and testing for evenness, now that you have 3 Fibonacci numbers, discard the eldest and repeat.
OP's present int fib_array[]={}; is not allocating the array needed for OP's approach. fib_array[i]= causes UB.
Per #Jules solution, even a long may be insufficient, consider long long. In anycase , use the matching prinf() format specifier. Edit: Turns out the answer is < 5,000,000, so long will work.
long sum_of_Even = 0;
....
printf("sum of Even terms in the fib sequence = %li\n", sum_of_Even);
#include <stdio.h>
#include <string.h>
int main()
{
long i,s=0,f[50];
f[0]=1;
f[1]=1;
for (i=2;f[i]<4000000;i++){
f[i] = f[i-1] + f[i-2];
if (f[i]%2 == 0){
printf("%ld ",f[i]);
s += f[i];
}
}
printf("SUM = %ld\n",s);
return 0;
}

Bus Error in C for Loop

I have a toy cipher program which is encountering a bus error when given a very long key (I'm using 961168601842738797 to reproduce it), which perplexes me. When I commented out sections to isolate the error, I found it was being caused by this innocent-looking for loop in my Sieve of Eratosthenes.
unsigned long i;
int candidatePrimes[CANDIDATE_PRIMES];
// CANDIDATE_PRIMES is a macro which sets the length of the array to
// two less than the upper bound of the sieve. (2 being the first prime
// and the lower bound.)
for (i=0;i<CANDIDATE_PRIMES;i++)
{
printf("i: %d\n", i); // does not print; bus error occurs first
//candidatePrimes[i] = PRIME;
}
At times this has been a segmentation fault rather than a bus error.
Can anyone help me to understand what is happening and how I can fix it/avoid it in the future?
Thanks in advance!
PS
The full code is available here:
http://pastebin.com/GNEsg8eb
I would say your VLA is too large for your stack, leading to undefined behaviour.
Better to allocate the array dynamically:
int *candidatePrimes = malloc(CANDIDATE_PRIMES * sizeof(int));
And don't forget to free before returning.
If this is Eratosthenes Sieve, then the array is really just flags. It's wasteful to use int if it's just going to hold 0 or 1. At least use char (for speed), or condense to a bit array (for minimal storage).
The problem is that you're blowing the stack away.
unsigned long i;
int candidatePrimes[CANDIDATE_PRIMES];
If CANDIDATE_PRIMES is large, this alters the stack pointer by a massive amount. But it doesn't touch the memory, it just adjusts the stack pointer by a very large amount.
for (i=0;i<CANDIDATE_PRIMES;i++)
{
This adjusts "i" which is way back in the good area of the stack, and sets it to zero. Checks that it's < CANDIDATE_PRIMES, which it is, and so performs the first iteration.
printf("i: %d\n", i); // does not print; bus error occurs first
This attempts to put the parameters for "printf" onto the bottom of the stack. BOOM. Invalid memory location.
What value does CANDIDATE_PRIMES have?
And, do you actually want to store all the primes you're testing or only those that pass? What is the purpose of storing the values 0 thru CANDIDATE_PRIMES sequentially in an array???
If what you just wanted to store the primes, you should use a dynamic allocation and grow it as needed.
size_t g_numSlots = 0;
size_t g_numPrimes = 0;
unsigned long* g_primes = NULL;
void addPrime(unsigned long prime) {
unsigned long* newPrimes;
if (g_numPrimes >= g_numSlots) {
g_numSlots += 256;
newPrimes = realloc(g_primes, g_numSlots * sizeof(unsigned long));
if (newPrimes == NULL) {
die(gracefully);
}
g_primes = newPrimes;
}
g_primes[g_numPrimes++] = prime;
}

Why is prime number check getting wrong results for large numbers?

This small C script checks if a number is a prime... Unfortunately it doesn't fully work. I am aware of the inefficiency of the script (e.g. sqrt optimization), these are not the problem.
#include <stdio.h>
int main() {
int n, m;
printf("Enter an integer, that will be checked:\n"); // Set 'n' from commandline
scanf("%d", &n); // Set 'n' from commandline
//n = 5; // To specify 'n' inside code.
for (m = n-1; m >= 1; m--) {
if (m == 1) {
printf("The entered integer IS a prime.\n");
break;
}
if (n % m == 0) {
printf("The entered integer IS NOT a prime.\n");
break;
}
}
return 0;
}
I tested the programm with a lot of numbers and it worked... Then I tried a bigger number (1231231231231236) which is clearly not a prime...
BUT: the program told me it was!?
What am I missing...?
The number "1231231231231236" is too big to fit in an "int" data type. Add a printf statement to show what number your program thinks you gave it, and if that's prime, your program works fine; else, you might have a problem that merits checking. Adding support for integers of arbitary size requires considerable extra effort.
The reason you are having this problem is that intrinsic data types like int have a fixed size - probably 32 bits, or 4 bytes, for int. Given that, variables of type int can only represent 2^32 unique values - about 4 billion. Even if you were using unsigned int (you're not), the int type couldn't be used to store numbers bigger than around 4 billion. Your number is several orders of magnitude larger than that and, as such, when you try to put your input into the int variable, something happens, but I can tell you what doesn't happen: it doesn't get assigned the value 1231231231231236.
Hard to know without more details, but if your ints are 32-bit, then the value you've passed is outside the allowable range, which will no doubt be represented as something other than the value you've passed. You may want to consider using unsigned int instead.
The given number is too large for integer in C. Probably it only accepted a part of it. Try Printing the value of n.

Resources