64 位函数返回 32 位指针 [英] 64 bit function returns 32 bit pointer

查看:31
本文介绍了64 位函数返回 32 位指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个函数被埋在一个复杂的嵌套中,所以实际上找到原因可能超出了我的要求,但我想知道是否有人能够提供一些关于我如何调试它的提示.这是我遇到问题的代码的要点

This function is buried in a complex nest so actually finding the cause is probably beyond anything I can ask, but I'm wondering if anyone might be able to give some tips on how I might go about debugging this. Here is the gist of the code I'm having trouble with

//func1.c
somestruct* func1(somestruct* mystruct)
{
    printf("func1: %p, %i
", mystruct, mystruct->foo);
    return mystruct;
}
//func2.c
somestruct* func1(somestruct* mystruct);
void func2()
{
    somestruct *mystruct = malloc(sizeof(somestruct));
    mystruct->foo = 10;
    printf("func2: %p, %i
", mystruct, mystruct->foo);
    mystruct = func1(mystruct);
    printf("back in func2: %p
", mystruct);
    free(mystruct);
}

我调用func2.输出是这样的

And I call func2. The output is like so

func2: 0x7f38a00008c0, 10
func1: 0x7f38a00008c0, 10
back in func2: 0xffffffffa00008c0
(SEGFAULT trying to free 0xffffffffa00008c0)

实际代码更复杂,mystruct"在许多其他地方也毫无问题地传递,函数位于不同文件中的事实似乎可能是问题的一部分,是的,它需要返回指针(不保证返回的指针与输入指针相同).对我来说,它有点(但实际上不是)被截断为 32 位,然后在顶部填充 ffffffff,这对我来说似乎很奇怪.

The actual code is more complex, "mystruct" gets passed around in many other places as well without issue, the fact that the functions are in different files seems like it might be part of the problem, yes it needs to return the pointer (the returned pointer is not guaranteed to be the same as the input pointer). It seems really weird to me that it's kind of (but not actually) getting truncated to 32 bits, and then filled with ffffffff at the top.

在 32 位机器上编译时,它的工作原理完全一样.

When compiled on a 32 bit machine it works exactly as it should.

我曾考虑过某处内存损坏,所以我通过 valgrind 运行它.Valgrind 没有报告任何错误,实际上使其成功完成.教科书heisenbug.至少我可以使用 GDB.

I'd considered memory corruption somewhere, so I ran it through valgrind. Valgrind reports no errors, and in fact causes it to complete successfully. Textbook heisenbug. At least I can use GDB.

有没有人知道是什么原因导致了这种情况,或者至少我可以如何开始追踪问题?

Does anyone have any idea what might be causing this, or at least how I might start tracking down the problem?

推荐答案

如果你错过了函数原型,请检查你的代码 (somestruct* func1(somestruct* mystruct);).in func2.c.

Check your code if you missed out function prototype (somestruct* func1(somestruct* mystruct);).in func2.c.

默认所有返回值都是整数.因此,如果函数缺少原型,则编译器会将返回值视为 32 位并为 32 位返回值生成代码.那就是你的高 4 个字节被截断的时候.

By default all return values are int. So if a prototype is missing for function then compiler treats the return value as 32-bit and generates code for 32-bit return value. Thats when your upper 4 bytes gets truncated.

这篇关于64 位函数返回 32 位指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆