【发布时间】:2015-10-17 23:37:24
【问题描述】:
我正在尝试将 malloc 的 ptr 保存在全局 ptr 中,以便可以在另一个函数中使用它。理想情况下,我会在全球范围内建立一个更智能的数据结构,但现在我只是想让全球 ptr 工作。
在我的 lwp.h 文件中,我有以下定义:
typedef struct threadinfo_st *thread;
typedef struct threadinfo_st {
tid_t foo1
unsigned long foo2
size_t foo3
rfile foo4
thread foo5
thread foo6
thread foo7
thread foo8
} context;
使用这个线程结构,我的 lwp.c 文件中有两个函数。在第一个函数中,我构造了一个 malloc 线程,然后将数据复制到全局 ptr。然后在第二个函数中,我尝试取消引用全局 ptr 以接收我最初创建的线程。为了确认我这样做是正确的,我在每一步都打印出 ptr 地址。不幸的是,我似乎无法恢复原来的地址,因此我在第二个函数中的所有数据都被转移了
static thread headThread = NULL;
void create(){
thread newThread = (thread) malloc( sizeof(thread));
assert(newThread != NULL)
// Assign junk to newThread
printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
headThread = newThread;
}
void start(){
thread newThread = headThread;
printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
}
在 main 中调用 create() 然后 start() 打印出来:
newThread is at: 0x7ffdf085c5e0, headThread is at: 0x601890
newThread is at: 0x7ffdf085c5d8, headThread is at: 0x601890
导致我在 start() 函数的 newThread 中的所有数据都被转移。
我还尝试了以下方法:
static thread *headThread = NULL;
void create(){
thread newThread = (thread) malloc( sizeof(thread));
assert(newThread != NULL)
// Assign junk to newThread
printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
headThread = &newThread;
}
void start(){
thread newThread = headThread;
printf("newThread is at: %p, headThread is at: %p\n", &newThread, &headThread);
}
打印出来:
newThread is at: 0x7ffff6294130, headThread is at: 0x601890
newThread is at: 0x7ffff6294128, headThread is at: 0x601890
有谁知道我在这种情况下到底做错了什么? 感谢您的帮助!
【问题讨论】:
-
thread newThread = (thread) malloc( sizeof(thread))没有意义。您正在尝试分配一个结构,而不是一个指针,所以sizeof(thread)是错误的。更好:thread newThread = malloc(sizeof *newThread);最好:不要将指针隐藏在 typedef 后面。 -
谢谢,我正在处理提供给我的用于多线程分配的头文件。我将把这个告诉我的教授,为什么他选择以这种方式构建它。感谢您的帮助!
-
请不要从您的问题中删除内容。你的问题仍然存在,否则答案没有意义。您的问题的旧版本仍然在网站上可见,只是从默认视图中隐藏。如果您不小心发布了机密数据,您可以将其删除,但首先您需要以现有答案仍然有意义的方式编辑您的问题,然后标记您的问题并要求旧版本已被删除 - 但请记住,它们已被 Google 索引。不过,我在您的原始问题中看不到任何机密内容。
标签: c multithreading pointers struct