Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C: Invalid Memory Access

I am new to C arrays and I am facing a problem that my code returns an error of invalid memory access.

Here is the exact error:

"Caught unexpected signal: SIGSEGV (11). Invalid memory access."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:

#include <stddef.h>

int factorial(int x) {               
    if (x == 0 || x == 1) {
        return 1;
    }
    else {
        return x * factorial(x - 1);
    }
}

unsigned long long sum_factorial(size_t z, const int array[z]) {
    unsigned long long result = 0;
    
   for (size_t i = 0; i < z; ++i) {
       result = result + factorial(array[z]);  
   }
   
   return result;
}

>Solution :

**small mistake in above code please replace array[z] with array[i] inside for loop ** Below I mentioned correct code please refer it.

#include <stddef.h>

int factorial(int x) {
    if (x == 0 || x == 1) {
        return 1;
    } else {
        return x * factorial(x - 1);
    }
}

unsigned long long sum_factorial(size_t z, const int array[z]) {
    unsigned long long result = 0;

    for (size_t i = 0; i < z; ++i) {
        result = result + factorial(array[i]); // error fix in here,
    }

    return result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading