这是我的代码,Tuple.c,它在该行产生一个 SegFault,并带有这样的注释:
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
void dbwait();
typedef struct STuple {
int tSize;
void** values;
} Tuple;
Tuple* CreateTuple(int n_args, ...) {
va_list varlist;
va_start(varlist, n_args);
int varsSize;
void** vars = (void**)malloc(n_args * sizeof(void*));
for (int i = 0; i < n_args; i++) {
void* arg = va_arg(varlist, void*);
varsSize += sizeof(arg);
vars[i] = arg;
printf("Arg ptr = %p\n", arg);
}
// Size of all of the arguments + size of an int value (varsSize) since Tuple has an array of void* and a single int.
Tuple* t = (Tuple*)malloc(varsSize + sizeof(varsSize));
t->values = vars;
t->tSize = n_args;
va_end(varlist);
return t;
}
void FreeTuple(Tuple* t) {
printf("Freeing tuple at %p\n", (void*)t);
free(t->values);
free(t);
}
int main(int argc, char** argv) {
Tuple* rt = CreateTuple(3, 625, 173, 50);
int length = rt->tSize;
printf("%i\n", length); // Prints 3, as defined in the call to CreateTuple
dbwait();
for (int i = 0; i < length; i++) {
printf("index = %i: ", i);
dbwait();
void* ptr = rt->values[i];
printf("At ptr %p, ", ptr); dbwait();
int value = *((int*)ptr); // SegFault Occurs here!
printf("with value = %d\n", value);
dbwait();
}
dbwait();
FreeTuple(rt);
return 0;
}
void dbwait() {
char* stop = (char*)malloc(sizeof(char));
scanf("%c", stop);
free(stop);
}
我确实知道分配给 ptr
的地址在ptr = rt->values[i];
是正确的,因为每当我复制从 gdb 打印的地址并执行 print (address) 时,它都会打印出正确的值 625。
本地址正确指向整数时,为什么我会收到 SegFault?
编辑:按照其他用户的要求,我已将问题的当前代码内容替换为上面所示的整个 tuple.c 文件。
最佳答案
如果 *ptr
为 625,则 *valPtr
正在取消引用地址 625。
如果您在调试器内运行它,请在取消引用时查看 valPtr 的值。
关于c - 从 void ptr 取消引用整数时出现 SegFault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044240/