【发布时间】:2015-10-05 01:08:57
【问题描述】:
假设我们在 C 文件中有以下结构定义:
typedef struct {
char *name;
int id;
int last_cpu;
} thread_t;
(这是我正在编写的模拟,用于为我的操作系统类使用不同的调度算法)。每次我创建一个新的thread_t 结构时,我该如何处理其中一个变量是char* 的事实?例如,我的代码中有以下方法:
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;
}
如果new_thread 的name 字段“太大”,我可能会遇到分段错误吗?也就是说,我应该在分配线程名称之前为它分配额外的内存吗?我试过运行它,它似乎表现得很好,但我担心它以后可能会中断。
【问题讨论】:
-
也不要在 C stackoverflow.com/a/605858/5339899 中转换 malloc 的值,你甚至不需要为 new_thread 分配内存
-
为什么我不需要为
threads分配内存?由于'threads是此函数返回的内容,如果我不为其分配内存,难道不会出现段错误吗? -
注意:
thread_t **threads = (thread_t **) malloc(MAX_NUM_THREADS * sizeof(thread *));的一个很好的简化是thread_t **threads = malloc(sizeof *threads * MAX_NUM_THREADS);。更易于维护且代码错误的可能性更低。 -
调用 malloc() 时不要强制转换返回值,因为返回值是
void *,所以可以分配给任何指针。始终检查 (!=NULL) 返回值以确保操作成功。
标签: c struct segmentation-fault malloc