0

I'm trying to allocate memory for an array inside a struct like this one:

    typedef struct
    {
        int a;
        int *b;
    } MyStruct;

I have a function to initialize the struct like this one:

    void init( MyStruct * myStruct, int size )
    {
        myStruct = malloc( sizeof( MyStruct ) );
        myStruct->a = size;
        myStruct->b = malloc( size * sizeof( int ) );
    }

But when I try to allocate memory for the fields inside the array b, I get the segmentation fault error

    int main( void )
    {
        int i, size = 5;
        MyStruct *myStruct;
        init( myStruct, size );

        for( i = 0; i < size; i++ )
        {
            myStruct->b[i] = malloc( sizeof( int ) ); //fails here
            myStruct->b[i] = i*i;
        }
    }

I tried searching over and over, but I was not able to solve this problem. Someone knows why this is happening?

0

2 Answers 2

5

Parameter passing in c is call-by-value, so the memory allocated in your init function is never assigned to the myStruct Pointer variable in main but only to its copy that is passed into init.

Sign up to request clarification or add additional context in comments.

Comments

1

First, you've already allocated five "slots" to put ints in there, so why would you need to call malloc again inside the loop? Second, there's no reason to create a pointer to MyStruct. So, third, there's no need to allocate memory for the whole structure.

void init( MyStruct * myStruct, int size )
{
    myStruct->a = size;
    myStruct->b = malloc(size * sizeof( int ));
}

int main(int argc, char *argv[])
{
    int i, size = 5;
    MyStruct myStruct;
    init( &myStruct, size );

    for( i = 0; i < size; i++ )
    {
        myStruct.b[i] = i*i;
    }

    free(myStruct.b);

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.