gpt4 book ai didi

c - 在结构中使用 posix_memalign 出现段错误

转载 作者:行者123 更新时间:2023-11-30 18:46:32 25 4
gpt4 key购买 nike

我现在面临着 posix_memalign 的问题,这可能是由我大脑中关于指针和变量的一个大结引起的。我已经有一段时间没有使用 C 语言了,需要再次找到我的方法。

我正在尝试使用 posix_memalign 分配一些内存,并希望使用数组结构中的指针作为我分配的内存的地址。

这基本上是我正在使用的方法,我不知道为什么会失败:

int init_const(void* data, int alignment, uint64_t size, int offset, DataType type, int stride, int numDomains){

int i;
size_t bytesize = 0;
int errorCode;
//int elements = 0;

size_t typesize = dataTypeLength(type);

bytesize = (size+offset) * typesize;
//int elements = alignment / typesize;

data = (void*)malloc(numDomains * sizeof(Datastruct));

//Allocating memory for array of datastructures
if(data == NULL){
fprintf(stderr,
"Error: Insufficient memory, can't even malloc array of pointers\n");
exit(EXIT_FAILURE);
}
for(i=0; i<numDomains; i++){
Datastruct* structure = (Datastruct*)data+sizeof(Datastruct)*i;
errorCode = posix_memalign(structure->a, alignment, bytesize);
printf("Hallo");
if (errorCode)
{
if (errorCode == EINVAL)
{
fprintf(stderr,
"Error: Alignment parameter is not a power of two\n");
exit(EXIT_FAILURE);
}
if (errorCode == ENOMEM)
{
fprintf(stderr,
"Error: Insufficient memory to fulfill the request\n");
exit(EXIT_FAILURE);
}
}
if (structure->a == NULL)
{
fprintf(stderr, "Error: posix_memalign failed!\n");
exit(EXIT_FAILURE);
}
}

return 0;

}

这是我的数据结构:

typedef struct {
void* a;
} Datastruct;

遗憾的是,这会导致 posix_memalign 出现段错误,我不知道我在这里做错了什么。这可能是某个地方的指针操作困惑,但我不知道在哪里。

最佳答案

man posix_memalign

是你的 friend 。您会在那里找到:

int posix_memalign(void **memptr, size_t alignment, size_t size);

所以它想要的是指针&struct->a的地址,而不是旧值struct->a

关于c - 在结构中使用 posix_memalign 出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775857/

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