mardi 28 juin 2016

SegFault when dereferencing integer from void ptr

This is my code, Tuple.c, it produces a SegFault at the line with a comment saying so:

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

void dbwait();

typedef struct STuple {
    int tSize;
    void** values;
} Tuple;

Tuple* CreateTuple(int n_args, ...) {
    va_list varlist;
    va_start(varlist, n_args);

    int varsSize;
    void** vars = (void**)malloc(n_args * sizeof(void*));

    for (int i = 0; i < n_args; i++) {
        void* arg = va_arg(varlist, void*);
        varsSize += sizeof(arg);
        vars[i] = arg;
        printf("Arg ptr = %pn", arg);
    }

    // Size of all of the arguments + size of an int value (varsSize) since Tuple has an array of void* and a single int.
    Tuple* t = (Tuple*)malloc(varsSize + sizeof(varsSize));

    t->values = vars;
    t->tSize = n_args;

    va_end(varlist);

    return t;
}

void FreeTuple(Tuple* t) {
    printf("Freeing tuple at %pn", (void*)t);
    free(t->values);
    free(t);
}

int main(int argc, char** argv) {
    Tuple* rt = CreateTuple(3, 625, 173, 50);

    int length = rt->tSize;

    printf("%in", length); // Prints 3, as defined in the call to CreateTuple
    dbwait();

    for (int i = 0; i < length; i++) {

        printf("index = %i: ", i);
        dbwait();

        void* ptr = rt->values[i];
        printf("At ptr %p, ", ptr); dbwait();

        int value = *((int*)ptr); // SegFault Occurs here!
        printf("with value = %dn", value);
        dbwait();
    }

    dbwait();

    FreeTuple(rt);

    return 0;
}

void dbwait() {
    char* stop = (char*)malloc(sizeof(char));
    scanf("%c", stop);
    free(stop);
}

I know for a fact that the address assigned to ptr at ptr = rt->values[i]; is correct since whenever I copy that address as its printed from gdb and do print (address), it prints out the correct value of 625.

Why am I getting a SegFault when the address correctly points to an integer?

EDIT: Clearly I need to say that I'm very new to C and have next to no experience with pointers, otherwise I'll get down voted for not knowing very much C. This experiment is a deep dive into handling pointers and dereferencing. I've replaced the current code content of my question with my entire tuple.c file, shown above.

Aucun commentaire:

Enregistrer un commentaire