0

I am trying to create dynamically an array of structs . Although with small sizes seems to work fine but the program crushes later(segmentation fault ) . When in have a big ipt_size it crushes very fast with nosense numbers so i assume the problem is in the way i allocate my array.

int create_ipt(int ipt_size,frame **ipt){
    int i;
    *ipt=malloc(ipt_size*sizeof(frame*));
 for(i=0;i<ipt_size;i++){
    ipt[i]=malloc(sizeof(frame));
     if (ipt[i]==NULL) return 1; //error
    ipt[i]->empty=1;
   }
 return 0; //success
}//create page table

I call the function with

     frame *ipt;
    create_ipt(ipt_size,&ipt);

Do you know what's happening ? frame has 3 ints inside

2
  • 1
    *ipt=malloc(ipt_size*sizeof(frame*)); --> *ipt=malloc(ipt_size*sizeof(frame));.. if (*ipt==NULL) return 1; for(i=0;i<ipt_size;i++){ (*ipt)[i].empty=1; } Commented Jan 13, 2017 at 16:31
  • Thank you man . That was the way . add your comment as an answer to make it green :) Commented Jan 13, 2017 at 16:46

2 Answers 2

2

Look at the type of *ipt, it is frame *, that means, it's a pointer to type frame, i.e., points to a type frame. So you need to allocate memory which is capable of holding type frame and allocate the address to *ipt.

Change the memory allocation to reflect the same. Change

 *ipt=malloc(ipt_size*sizeof(frame*));

to

*ipt=malloc(ipt_size*sizeof(frame));

Then, have a look and revise (remove) the following statement ipt[i]=malloc(sizeof(frame));, you have already allocated memory for holding ipt_size number of elements.

After that, look at the dereference statement. Instead of

ipt[i]->empty=1;

you need to write

(*ipt)[i].empty = 1;

and that explicit parenthesis is there because of (to avoid the unwanted effect of) operator precedence.

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

Comments

0

In create_ipt, you use:

ipt to access **ipt (pointer to the pointer you created in the main)

*ipt to access *ipt (pointer to the struct frame)

**ipt to access ipt (struct frame itself)

int create_ipt(int ipt_size, frame **ipt)
{
        int i;
        *ipt = malloc(ipt_size*sizeof(frame*)); // *ipt is the pointer to the struct frame you want to allocate memory)
        for(i=0; i < ipt_size; i++)
        {
                // If you only have integers you don't need to allocate memory to the struct, it's already allocated, but if you have char* you should malloc that var
                (*ipt)[i].text = malloc(text_size*sizeof(char));
                (*ipt)[i].empty = 1;
        }
        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.