while I was programming on codewars, I encountered an error called signal 6.
The program works correctly on most unit tests, but takes error on one of them: Test Crashed Caught unexpected signal: 6
If you know what could be the cause of the error, I would be glad for your help. Thanks!
This is assignment conditions:
The aim of the kata is to decompose n! (factorial n) into its prime factors.
Examples:
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11" since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.
n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"
n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23 Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent.
Notes: the function is decomp(n) and should return the decomposition of n! into its prime factors in increasing order of the primes, as a string. factorial can be a very big number (4000! has 12674 digits, n can go from 300 to 4000). In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.
And this is my solution:
#include <stdlib.h>
char *func(char* p, int num);
char *decomp(int n)
{
int size = 100;
int* p = (int*)malloc(sizeof(int) * size);
char* res = (char*)malloc(sizeof(char) * 200);
char* res2 = res;
for (int i = 0; i < size; i )
{
*(p i) = 0;
}
for (int i = 2; i <= n; i )
{
for (int j = 2, k = i; k > 1;)
{
if (k % j == 0)
{
while (j > size)
{
size = 100;
p = (int*)realloc(p, size);
}
*(p j) = 1;
k /= j;
}
else
{
j ;
}
}
}
for (int i = 0; i < size; i )
{
if (*(p i) != 0)
{
res = func(res, i);
if (*(p i) != 1)
{
*(res ) = '^';
res = func(res, *(p i));
}
*(res ) = ' ';
*(res ) = '*';
*(res ) = ' ';
}
}
*(res - 3) = '\0';
return res2;
}
//takes a pointer to memory and convert there integer to str
char *func(char* p, int num)
{
int len = 0;
for (int i = 1; num / i > 0; i *= 10)
len ;
char* p2 = (char*)malloc(sizeof(char) * len 4);
while (num > 0)
{
*(p2 ) = (num % 10) '0';
num /= 10;
}
p2--;
for (int i = 0; i < len; i )
{
*(p ) = *(p2--);
}
*p = '\0';
return p;
}
CodePudding user response:
The problem is with your realloc
statement. You have:
while (j > size)
{
size = 100;
p = (int*)realloc(p, size);
}
where it should be
while (j > size)
{
size = 100;
p = (int*)realloc(p, sizeof(int)*size);
}
since you are allocating an array if ints and sizeof(int) > 1
you are not
allocating enough memory. This is causing you to write to memory you have
not allocate and with large enough arguments to decomp
causing you to write
to illegal addresses.
This causes you program to be killed with SIGABRT
which is usually signal 6.