gpt4 book ai didi

c - 线程改变堆内存

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:36 25 4
gpt4 key购买 nike

我正在编译这个程序。

char * p;    
void * handler(void * arg)
{
p = "hello"; // initializing p
puts(p);
puts("------");
long tid = (long) arg;
printf("Hello wrold! it is in thread : %ld\n", tid);
pthread_exit(NULL); //exiting thread
}

int main() {
pthread_t t_id[2];
int rc;
long t;
p = malloc(sizeof(100)); // allocating memory tried (p =malloc(sizeof(char)*100);)
if (p == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}


for (t = 0; t < 2; t++) {
printf("Creating Thread %ld\n", t);
rc = pthread_create( & t_id[t], NULL, handler, (void * ) t);
if (rc) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
pthread_join(t_id[0], NULL);
pthread_join(t_id[1], NULL);
free(p); /// segmentation fault here...
puts("***");
// pthread_exit(NULL);

}

我在这里遇到段错误,我使用 gdb 检查过。令人惊讶的是,p 的地址正在改变。为什么?

任何帮助之手将不胜感激!

使用主机 libthread_db 库“/lib/x86_64-linux-gnu/libthread_db.so.1”。

Temporary breakpoint 1, main () at thread_heap.c:27
27 p=malloc(sizeof(100));
(gdb) p p
*$1 = 0x0* **/// adress of p**
(gdb) next
28 if(p==NULL)
(gdb) p p
*$2 = 0x602010 ""* **// why changed here????**
(gdb) next
35 for (t=0;t<2;t++)
(gdb) p p
$3 = 0x602010 ""
(gdb) next
37 printf("Creating Thread %ld\n",t);
(gdb)
Creating Thread 0
38 rc=pthread_create(&t_id[t],NULL,handler,(void *)t);
(gdb)
[New Thread 0x7ffff77fe700 (LWP 21632)]
.
.
.

114 in pthread_join.c
(gdb)
main () at thread_heap.c:49
49 free(p);
(gdb) p p
*$4 = 0x4009e0 "hello"* **/// again why changed here?**
(gdb)
$5 = 0x4009e0 "hello"
(gdb) step
__GI___libc_free (mem=0x4009e0) at malloc.c:2959
2959 malloc.c: No such file or directory.
(gdb) q

Program received signal SIGSEGV, Segmentation fault.
_int_free (av=0x7ffff7bb6720, p=0x4009d0, have_lock=0) at malloc.c:4098
4098 malloc.c: No such file or directory. // Why this address changed?
(gdb)

最佳答案

问题在

// in main
p = malloc(sizeof(100)); // allocating memory tried (p =malloc(sizeof(char)*100);)

// in handler function
p = "hello"; // initializing p

这里的p是一个全局变量,你之前已经在它上面使用了malloc。在处理程序函数中,您将 p 分配给字符串文字的地址,从而导致悬空指针。当您尝试释放这个修改后的 p 时,您会收到一个错误。

你应该做的是

const char *hell = "hello";
strcpy(p,hell);

此外,将 malloc 修复为您之前拥有的。当前代码仅分配 4 个字节。 (sizeof (100)sizeof(int) 相同)

关于c - 线程改变堆内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41583401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com