【问题标题】:Runtime error while returning dereferenced pointer's value from a function in C从 C 中的函数返回取消引用指针的值时出现运行时错误
【发布时间】: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


【解决方案1】:

正如n. m. 所说,在scanf(formatSpecifier, ptr); 内的第3 行,您使用了一个未初始化的指针。 void *ptr;未初始化,这意味着您没有决定它指向的位置,但随后尝试使用它,尝试在无法访问的内存上写入错误

Ox000000000040002C 处的指令引用了 Ox000000000000002C 处的内存。无法写入内存。

指出。在这种情况下,Ox000000000040002C 是您的 ptr 的索引,而 Ox000000000000002C 是它指向的索引(它可能会有所不同,因为您没有初始化您的指针)。

我相信您可以在this here. 上阅读更多内容

旁注:在您的问题中,您解释了一个函数 GetShort() 但在提供的代码中使用了一个函数 GetInt() 。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2020-03-20
    • 2018-08-19
    • 2013-07-01
    相关资源
    最近更新 更多