Suppose that we have the following struct definition in a C file:
typedef struct {
char *name;
int id;
int last_cpu;
} thread_t;
(this is for a simulation I'm writing to play with different scheduling algorithms for my OS class). Every time I create a new thread_t
struct, how do I deal with the fact that one of the variables is a char*
? For example, I have the following method in my code:
thread_t **get_starting_thread_list() {
thread_t **threads = (thread_t **) malloc(MAX_NUM_THREADS * sizeof(thread *));
int next_id = 0;
for (int th_num = 0; th_num < MAX_NUM_THREADS; th_num++) {
thread_t *new_thread = (thread_t *) malloc(sizeof(thread_t));
new_thread->name = "New thread";
new_thread->id = ++next_id;
new_thread->last_cpu = 0;
threads[th_num] = new_thread;
}
return threads;
}
Could I potentially get a Segmentation Fault if the name
field of new_thread
is ever "too big"? That is, should I be allocating additional memory for the thread name before assigning it? I've tried running this and it seems to be behaving fine, but I'm afraid that it could potentially break later on.