0

I'm having some difficulty figuring out why my program is segfaulting. Any help? Some context: This is a coding assignment where I run this method through a program that executes with various inputs and determines if the function is correct or not. The purpose of this assignment is to read assembly and construct a function based on the given assembly.

I don't think it's the comp4 method, because I've compared it to the given assembly, and it's identical, which suggests it's in the problem4 method, but I have no idea what's in problem 4 that could even cause a seg fault. Could anyone offer any help?

long int comp4(long int * a, long int b) {
  long int output = *a;
  long int newa = output + b;
  *a = newa;
  return output;
}

long int problem4(long int a, long int b){
int i;
long int* ap;
*ap = a;
long int sum;
long int holder;
for (i=0;i<b;i++){
  sum = sum + i*8;
  holder = comp4(ap,2);
  sum = sum + holder;
}
return sum;
}
wtk219
  • 285
  • 1
  • 9

1 Answers1

0

ap is an uninitialized pointer. When you declare long int *ap it allocates a memory on the stack that can hold the address of a long int * but it does not allocate the memory for a variable to which this pointer can point.

So, you need to initialize your pointer value, before you can dereference it using the * operator.

A more appropriate approach would be ::

long int *ap = &a;

or

long int *ap = malloc(sizeof(long int));
*ap = a;

Dereferencing a non-initialized pointer is the reason your program segfaults!

user007
  • 2,156
  • 2
  • 20
  • 35