Pages

Thursday, March 9, 2017

C Casting Question

Feeling like the casting part of my brain didn't survive the stroke.

void* value;   // Contains address of either a float or int &floatVar or &intVar

int* target = (int*)value;   // Grab that pointer and make it a pointer to int
*target = 1;                        // store int value into intVar

I am successfully passing value to sscanf for floatVar
This compiles fine, but segmentation fault when it does the last line.

Just to clarify: value is part of a struct in an array, and value has been set to &suppressProlog which is an int.  In other array elements, value = &float variable, and works fine.  Curiously, &suppressProlog is not initialized in the array.  Chasing this down is what I need to do.

The problen is that the value above is flags[flagsIndex].valueAddr and after the switch statement that drops me to this case, flagsIndex has changed from 17 to -1073743768 which causes the segmentation error.  I don't see how the switch statement could change flagsIndex, but I will replace it with if...elseif...

Looking at the surrounding code makes me wonder how late at night I wrote this mess.
Cleaned up the disastrous code, problem solved.  Code after break in a switch case is not recommended.


2 comments:

  1. I don't think there's a problem with the cast, but "value" is never given a value (despite its name, heh). Try something like

    value = malloc(sizeof(int));

    ReplyDelete
  2. Thanks for clarifying. In the sense that I have no idea what's going on.

    Google tells me that

    -1073743768 = -0x40000798

    which, with all those 0s, makes me think "alignment issue"? Sorry, it's been a real long time since I seriously programmed in C.

    Do these printfs all give the same answer?

    printf("Size of void * = %d\n", sizeof(void *));
    printf("Size of int * = %d\n", sizeof(int *));
    printf("Size of float * = %d\n", sizeof(float *));

    ReplyDelete