Here is a C function that segfaults:

```
void compileShaders(OGL_STATE_T *state) {

    // First testing to see if I can access object properly. Correctly outputs:
    // nsHandle: 6
    state->nsHandle = 6;
    printf("nsHandle: %d\n", state->nsHandle);

    // Next testing if glCreateProgram() returns proper value. Correctly outputs:
    // glCreateProgram: 1
    printf("glCreateProgram: %d\n", glCreateProgram());

    // Then the program segfaults on the following line according to gdb
    state->nsHandle = glCreateProgram();

}

```

For the record state->nsHandle is of type GLuint and glCreateProgram() returns a GLuint so that shouldn't be my problem.

gdb says that my program segfaults on line 303 which is actually the comment line before that line. I don't know if that actually matters.

Is gdb lying to me? How do I debug this?

**EDIT:**

Turned off optimizations (-O3) and now it's working. If somebody could explain why that would be great though.

**EDIT 2:**
For the purpose of the comments, here's a watered down version of the important components:

```
typedef struct {
    GLuint nsHandle;
} OGL_STATE_T;

int main (int argc, char *argv[]) {
    OGL_STATE_T _state, *state=&_state;
    compileShaders(state);
}

```

**EDIT 3:**
Here's a test I did:

```
int main(int argc, char *argv[]) {

    OGL_STATE_T _state, *state=&_state;

    // Assign value and try to print it in other function
    state->nsHandle = 5;

    compileShaders(state);

}

void compileShaders(OGL_STATE_T *state) {

    // Test to see if the first call to state is getting optimized out
    // Correctly outputs:
    // nsHandle (At entry): 5
    printf("nsHandle (At entry): %d\n", state->nsHandle);

}

```

Not sure if that helps anything or if the compiler would actually optimize the value from the main function.

**EDIT 4:**
Printed out pointer address in main and compileShaders and everything matches. So I'm gonna assume it's segfaulting somewhere else and gdb is lying to me about which line is actually causing it.