Reputation: 151
I currently have a problem with my C code concerning RAM writes that appear to happen (I checked by watching a member of a structure via gdb) even though I did not actively intend to write to that area.
My structs are declared as followed:
typedef struct tcb {
unsigned int tid;
thread_state_t state;
pthread_t thread;
sem_t sema;
unsigned long interval;
unsigned long rtime;
} tcb_t ;
typedef struct node {
tcb_t *tcb;
} node;
typedef struct entry entry;
typedef struct entry {
entry *next;
entry *prev;
node node;
} entry;
These definitions are provided and I can not change them.
I now initialize an array of entry
with this code:
entry = malloc((num_threads) * sizeof(entry));
for (i = 0; i < num_threads; i++)
{
entry[i].next = NULL;
entry[i].prev = NULL;
entry[i].node.tcb = malloc(sizeof(tcb_t));
entry[i].node.tcb->tid = i;
entry[i].node.tcb->state = THREAD_RUNNABLE; //initialize value to show the scheduler this thread works for the first time
entry[i].node.tcb->interval = interval;
}
The other fields are not meant to initialized at this point. However once I run my code with let's say num_threads = 6
, the value for entry[0].node.tcb->tid
lost its value 0 but holds something strange (looks like a pointer to me).
When setting a watchpoint in gdb for this field it notifies me at the line entry[i].node.tcb = malloc(sizeof(tcb_t));
that my value was overwritten (at this point i
holds the value 2). Why is this?
Upvotes: 2
Views: 78
Reputation: 34585
You cannot have the line
entry = malloc((num_threads) * sizeof(entry));
as written - it does not compile. Since your program has lines such as
entry[i].next = NULL;
I guess it is actually
entry *entry = malloc((num_threads) * sizeof(entry));
So now what is sizeof(entry)
? My little test program tells me it is 4
, the size of the pointer, not the struct.
So please use unique identifiers.
Upvotes: 4