Glove
Glove

Reputation: 960

process structure memory allocation in C

EDIT:

Typedef struct SPro{
     int arrivalTime;
     char processName[15];
     int burst;
} PRO;

I have an array of type PRO

PRO Array[100];
PRO enteringProcess;
//initialize entering process

then I need to creat a new process and allocate memory for that process using malloc Then point the pointer from the array to the memory chunk that malloc returns.

PRO *newPro = (PRO *) malloc (sizeof(PRO));
newPro = enteringProcess;
ProArray[0] = *newPro;

It seems that I'm doing something wrong since my program crashes at run-time. Any help? thanks!

Upvotes: 0

Views: 565

Answers (3)

Soren
Soren

Reputation: 14718

Why do you need to allocate memory, the declaration

  PRO Array[100];

Already allocated the memory -- that is assuming your definition of PRO is something like;

  typedef struct {
     .....
  } PRO;

Revieweing your code;

// Declare a new pointer, and assign malloced memory
PRO *newPro = (PRO *) malloc (sizeof(PRO));

// override the newly declared pointer with something else, memory is now lost
newPro = enteringProcess;

// Take the content of 'enteringProcess' as assigned to the pointer, 
// and copy the content across to the memory already allocated in ProArray[0] 
ProArray[0] = *newPro;

You probably want something like this instead;

  typedef struct {
     ...
  } PRO;

  PRO *Array[100]; // Decalre an array of 100 pointers;

  PRO *newPro = (PRO *) malloc (sizeof(PRO));
  *newPro = enteringProcess;  // copy the content across to alloced memory
  ProArray[0] = newpro; // Keep track of the pointers

Upvotes: 5

zmbq
zmbq

Reputation: 39059

I'm guessing enteringProcess points to an invalid place in memory.

newPro = enteringProcess

is your problem.

Upvotes: 0

rodrigo
rodrigo

Reputation: 98516

Seems you need an array of pointers to PRO:

PRO *Array[100];

PRO *newPro = (PRO *) malloc (sizeof(PRO));
/* ... */
Array[0] = newPro;

I don't know what that enteringProcess is, so I cannot give opinion. Just that you should not assign anything to newPro other than the return of malloc or else you will leak the new object.

Upvotes: 1

Related Questions