c - 如何与Linux中的线程共享主程序的内存

标签 c linux memory pthreads share

我已经编辑了我的问题。线程的运行方式似乎与我的预期不同(Windows 与 Linux)。这是完整的工作示例:

#include <pthread.h>
#include <stdio.h>
#include <string.h>

void *testing(void *mptr)
{
char *mystr;
mystr=(char *)mptr;
printf(mystr);
printf("finished running thread\n");
return NULL;
}

int main()
{
pthread_t mythread;
char *str1;

str1=malloc(50);
strcpy(str1,"Hello World\n");
printf(str1);
printf("About to start\n");

//pthread_create(&mythread, NULL, testing, str1);

printf("finished creating thread\n");
printf(str1);
free(str1);
return 0;
}

以上程序产生:

Hello world
About to start
finished creating thread
Hello World

请注意,我没有在其中创建线程 - 具体行已被注释掉。 然而,如果我不注释掉“pthread_create..”行,输出是零星的,有时有垃圾:

Hello world
About to start
finished creating thread
Hello World
&%¤&finished creating thread

有时乱码部分还好,有时显示为“o World”等

根据我在 google 上搜索到的信息,堆栈的共享方式与 Windows 的共享方式不同。

如何访问稍后在线程中主程序中分配的内存?我错过了什么吗?

最佳答案

也许您应该等待线程完成后再释放字符串?

pthread_join 是你的 friend 。

关于c - 如何与Linux中的线程共享主程序的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775548/

相关文章:

c - 即时将程序输出重定向到文件,无需从批处理文件中缓冲

memory - 在不复制内存的情况下重复 pytorch 张量

c - 是否有任何资源或书籍可以帮助您了解 load_elf_binary 函数?

linux - 新的Ubuntu 14.04 VPS,无法以新用户身份登录

linux - 在 bash 中使用从字符串解析的数组

c - 获取动态加载库的地址空间

memory - 哪种 channel 类型在 Go 中使用最少的内存?

c - 带有 icd 指针的 C 代码中的 Valgrind 错误

c - C标准库中的函数在哪里定义的?

c - gcc/clang 如何假定字符串常量的地址是 32 位的?