For the following code:
#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;
}
I am getting a segmentation fault in threadFunc(). The program prints correctly for i=0, but gives a segmentation fault for all i > 0. Where is it that I am going wrong?
int main{looks wonky - what compiler are you using? If this is supposed to be standard C, please test to compile your code before posting.&sp+iis not what you want. It takes the address ofspand addsito it. But there are no other pointer after the single one.