我正在尝试将一个结构指针传递给一个函数,但是当我尝试访问该结构时,该结构内的最后一个变量在其内存地址中丢失了 1 个字节,导致使用该变量的任何内容发生段错误。
typedef struct
{
pthread_t tID;
int tType;
}sThread;
sThread threads[MAX_THREADS];
typedef struct
{
int tID;
int sock;
int arg_count;
char *from_p, **arg_p;
}command_struct;
pthread_t Thread_Start(void *function, void *param)
{
pthread_t tHandle;
pthread_create(&tHandle, NULL, function, (void*)param);
return tHandle;
}
void cmd_test(int sock, char *from_p, char **arg_p, int arg_count)
{
if(thread_check(1))
{
send_line(sock, "%s :test thread already running", from_p);
return;
}
command_struct test;
test.tID = thread_add(1);
test.arg_count = arg_count;
test.arg_p = arg_p;
threads[test.tID].tID = Thread_Start(test_cmd, &test);
}
void *test_cmd(void *param)
{
command_struct test = *((command_struct *)param);
int i = 0;
for(i = 1; i < test.arg_count; i++)
{
printf("%s", test.arg_p[i]);
}
thread_clear(test.tID);
return NULL;
}
在 cmd_test(生成线程的函数)内部发生的事情结构被正确初始化并且所有变量都是正确的。
$1 = {tID = 0, sock = 5, arg_count = 5, from_p = 0xbffff254 "test", arg_p = 0xbfffec48}
但是从正在运行的线程内部的 test_cmd 开始,结构缺少 arg_p 地址的 1 个字节,导致:
$1 = {tID = 0, sock = 5, arg_count = 5, from_p = 0xbffff254 "test", arg_p = 0xffec48}
如果我在我的 command_struct arg_p 地址的末尾添加一个无用的变量然后变得正确并且 command_struct 中的最后一个变量从它的内存地址中丢失 1 个字节。
最佳答案
您将一个指向局部变量的指针传递给您的线程 - 当线程访问它时,内存已被重新用于其他用途。
试试这个:
void cmd_test(int sock, char *from_p, char **arg_p, int arg_count)
{
if(thread_check(1))
{
send_line(sock, "%s :test thread already running", from_p);
return;
}
// === begin modified code in cmd_test():
command_struct* test = malloc(sizeof(command_struct));
test->tID = thread_add(1);
test->arg_count = arg_count;
test->arg_p = arg_p;
threads[test.tID].tID = Thread_Start(test_cmd, test);
// === end modified code
}
void *test_cmd(void *param)
{
command_struct test = *((command_struct *)param);
free(param); // <-- new line of code
// remainder is the same...
// ...
}
关于c - 将结构作为空指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13464721/