-2

The following code is a solution to a problem of finding amicable pairs between input numbers. I don't yet know if the algorithm is the best it can be, but what my problem is exactly is that the code below keeps on returning segmentation fault:11. I check and it doesn't even get to the for loop in the readNums function. Any suggestions what is wrong?

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

/*saves memory for a given length */
int *saveMemory(int sz) {
  int *ptr = calloc(sz, sizeof(int));
  if (ptr == NULL) {
    printf("Error: memory allocation failed (out of memory?).\n");
    exit(-1);
  }
  return ptr;
}

int *readNums(int length){

  int *nums = saveMemory(length), i;

  for (i = 0; i < length; i++){
    scanf("%d", &nums[i]);

  }
  return nums;

}

int divArr (int n) {
int i=0;

int j;
  int *arr = saveMemory(sizeof(arr)*4);

  for (j=1; j<n; j++) {

    if (n%j==0){
      arr[i]=j;
      i++;
    }


  }

  return arr;

}

int sumDiv (int *arr){
int sum, i;

for (i=0; i< sizeof(arr); i++){

    sum += arr[i];
  }

  return sum;
}


int main(int argc, char *argv[]) {
  int i, j, k, length;
  int *nums;

  printf("Please give me the length \n");
  scanf("%d", &length);
  printf("Please type in the numbers to be checked \n");
  nums = readNums(length);



  for (k=0; k<length-1; k++) {
    int a,b;
    int *arr;
    a=divArr(nums[i]);
    b=divArr(nums[k]);

    if (((sumDiv(a)) == nums[k]) && ((sumDiv(b)) == nums[i])) {

      printf("%d %d \n", i, j);


    } else {
      i++;

    }

  }


}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Kinga
  • 1
  • whats your input and expected output? – smushi Oct 04 '14 at 15:09
  • 4
    `a=divArr(nums[i]);` : `i` is not initialize. – BLUEPIXY Oct 04 '14 at 15:11
  • 2
    `sumDiv` is bad: It always sums the first `sizeof(int*)` elements of the passed array. Also, there are many uninitialized variables in `main`, one of which BLUEPIXY named. Did you compile it with all warnings enabled? `-Wall -Werror -pedantic`? – Deduplicator Oct 04 '14 at 15:12
  • Why are you allocating an array that's four times the number of array elements than you apparently need? `int *arr = saveMemory(sizeof(arr)*4);` Did you forget that `calloc` already knows the size of `int`? – Robert Harvey Oct 04 '14 at 15:13
  • 1
    `int *arr = saveMemory(sizeof(arr)*4);` should be `int *arr = saveMemory(sizeof(*arr)*(n-1));` also `return arr;` : type of `arr` is not `int`. – BLUEPIXY Oct 04 '14 at 15:14
  • don't you see any warnings. – µtex Oct 04 '14 at 15:18

1 Answers1

0
  1. change int divArr (int n) to int *divArr (int n).
  2. change int a,b; to int *a,*b; in main.

I didn't check your logic

µtex
  • 900
  • 5
  • 12