Home > Enterprise >  Algorithm causes segmentation fault
Algorithm causes segmentation fault

Time:01-02

I have built an algorithm that follows the following:

input n
print n
if n = 1 then STOP
if n is odd then n ←− 3n   1
else n ←− n/2 GOTO 2

Whereby if n = 22 this should print out:

22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

Given an input n, it is possible to determine the number of numbers printed before and including the 1 is printed. For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.

Therefore I have to determine the cycle-length between and including two integers i,j respectively.

#include <stdlib.h>
#include <stdio.h>

#define MAXSIZE 100
int test(int i, int j){
    int* z[MAXSIZE];
    int n = j-i;
    int *p;
    p = &j;
    int o = 0;
    while(&free){
        int k = 0;
        printf("\n%d -> %d ->> %d & %d", i, j, n, *p);
        while(&free){
        if (i == 1){
            break;
        } else if ((i % 2) != 0)
        {
            i = 3*i 1;
        } else{
            i = i/2;
        }
        k  ;
    }
    (*z)[o] = k;
    o  ;
    
    if (n == 1){
        break;
    }
        n--;
        i = *p-n;
    }
    size_t size = sizeof(z)/sizeof(z[0]);
    int m = 0;
    for (int i = 0; i < size; i  ){
        //printf("\n RESULTS: -- %d", (*z)[i]);
        if (m < (*z)[i]){
         m = (*z)[i];
        } else {
            continue;
        }
    }
    return m;
}

int main(){
    int i=900;
    int j=1000;
    int result;
    result = test(i,j);
    printf("\n RESULT: %d", result);
    return 0;
}

However, this is producing a segmentation fault which it caused my pointer deficiency, however, I cannot locate it.

UPDATE: Based on the comments, I believe the programme now runs as intended

CodePudding user response:

"producing a segmentation fault " that is because (*z) is UB.
z is an uninitialized array of pointers.

CodePudding user response:

this works fine

#define MAXSIZE 10000000
int test(int i, int j){
    static int* z[MAXSIZE];
    int n = j-i;
    int o = 0;

using static causes the array to be allocated in the programs static dta segment rather than the stack

  •  Tags:  
  • c
  • Related