Home Ask Login Register

Developers Planet

Your answer is one click away!

KLIK February 2016

Incrementing member of struct segfaults

I'm trying to increment a value of a struct (an int) just to test a code snippet of mine (This isn't my entire code), just the point of focus of my question. I'm given the struct:

typedef struct Test Test;
typedef struct Test {
    char * name;
    int numOfElements;
    Test * test[];

As well as the functions:

void startFunc(Test ** newStruct) {

    newStruct = malloc(sizeof(Test));

    (*newStruct)->name = NULL;
    (*newStruct)->numOfElements = 0;



void func(Test ** newStruct) {



//create function to later free allocated memory

However incrementing the value of numOfElements seems to segfault. Is it the fact that I didn't allocate enough memory (Since I'm using a flexible array member?)

I tried using valgrind and got a invalid read of size 8 on the (*newStruct)->name =NULL;

Which would suggest it's not malloced, Memory help here would be much appreciated,


AnT February 2016

malloc(sizeof(Test)) is intended to allocate a raw object of type Test, so conceptually it returns a Test * pointer. This pointer is assigned to newStruct, which is a Test **. This mismatch between Test * and Test ** already suggests that the malloc line is broken.

An immediate guess would be that this

newStruct = malloc(sizeof(Test));

was actually intended to be

*newStruct = malloc(sizeof(Test));

You are already scrupulously using *newStruct everywhere in your startFunc, but for some reason completely forgetting about it in the malloc line.

An arguably better way to express the same thing would be

*newStruct = malloc(sizeof **newStruct);

Post Status

Asked in February 2016
Viewed 2,937 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life