【发布时间】:2022-11-13 23:33:02
【问题描述】:
尝试运行下面的代码时出现运行时错误。
- 函数 get() 返回存储用户输入的空指针。
- 函数 getShort() 调用 get() 函数并在返回其值之前对指针进行类型转换并取消对 short 的引用。
- 虽然值在 getShort() 中工作得非常好;任何其他调用它的方法都会得到以下运行时错误。
The instruction at Ox000000000040002C referenced memory at Ox000000000000002C. The memory could not be written.
void * get(char formatSpecifier[]){
void *ptr;
scanf(formatSpecifier, ptr);
return ptr;
}
int getInt(){
int i = *(int *)get("%d");
printf("Works perfectly fine here: %d", i);
return i;
}
int main(){
int j = getInt(); // Error thrown here.
prinf("The value is : %d", j); // Does not print;
return 0;
}
任何帮助或反馈表示赞赏。 非常感谢。
【问题讨论】:
-
您将未初始化的
ptr传递给scanf。这会调用未定义的行为。指针需要指向要使用的东西。 -
我刚刚将代码修改如下,现在工作正常。
void *ptr = malloc(sizeof(int));非常感谢您的帮助。 -
@NischalTiwari:这并不能像您认为的那样解决问题。也许从正确使用
scanf开始而不尝试使用get包装器? -
现在它有一个内存泄漏.无论如何,
int i = *(int *)get("%d");比int i; scanf("%d", &i);简单吗?
标签: c pointers runtime-error