【发布时间】:2021-11-22 08:32:22
【问题描述】:
对于以下代码:
#include<stdatomic.h>
int *sp;
int threadFunc()
{
int *p;
for(int i = 0; i < 10; i++){
p = __atomic_load_n(&sp+i, __ATOMIC_SEQ_CST);
printf("Value loaded = %d from %p", *p, p);
}
return 0;
}
int main(int argc, char *argv[])
{
int a = 0;
sp = malloc(sizeof(int)*10);
if(sp == NULL){
printf("Not enough memory\n");
return -1;
}
// initialize the contiguous array pointed by sp with zero
for(int i = 0; i < 10; i++){
memcpy((void*)sp+i, &a, sizeof(int));
}
// call the following function on different thread
threadFunc();
return 0;
}
我在threadFunc() 中遇到分段错误。该程序为i=0 正确打印,但为所有i > 0 给出了分段错误。我哪里错了?
【问题讨论】:
-
您不需要强制转换为 void*。 (并且您的程序中没有指针数组)
-
int main{看起来很奇怪——你使用的是什么编译器?如果这应该是标准 C,请在发布之前测试以编译您的代码。 -
@RestingPlatypus:不,你没有。
-
请把代码放上来,你可以自己编译。如果这确实为您编译,请说明您正在使用什么编译器(和选项)。
-
&sp+i不是你想要的。它获取sp的地址并将i添加到其中。但是在单个指针之后没有其他指针。
标签: c pointers segmentation-fault