Ross Satchell Ross Satchell - 3 months ago 8
C Question

C pointers segmentation fault confusion

I am learning pointers and going through the examples from this Stanford PDF
Stanford Pointers Guide

I decided to write some code using their examples to get a better handle on what is happening. I am working from page 21 of the PDF.

When I run the code I get a segmentation fault, so I know that I'm trying to access memory that doesn't belong to me, but I don't understand where I'm going wrong.

Here is the code I have written:

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

// function prototypes
void C();
void B();

void main(){
int *worthRef;
int num = 42;
worthRef = &num;
B(*worthRef);
}

// Takes value of interest by reference and adds 2
void C(int* worthRef){
*worthRef = *worthRef + 2;
printf("num = %d", &worthRef);
}

// adds 1 to value of interest then calls C()
void B(int* worthRef){
*worthRef = *worthRef + 1; // add 1 to worthRef as before

C(worthRef); // NOTE: no & required. We already have a pointer to
// the value of interest, so it can be
// passed through directly
}

Answer
// function prototypes
void C();
void B();

That comment is a lie. Those are function declarations without a prototype (which is part of the problem in this code).

    B(*worthRef);

This line calls B with an int. (Given the declaration int *worthRef, the type of *worthRef is int.)

void B(int* worthRef){

But here B expects to be given a pointer to an int, which is the bug: You're passing a number where a pointer is expected.


To fix this, change the call in main to B(worthRef) (or B(&num)), and change

    printf("num = %d", &worthRef);

to

    printf("num = %d\n", *worthRef);

If you had included a prototype in your function declarations, then the compiler would have warned you about the problem (probably):

// function prototypes
void C(int *);
void B(int *);
Comments