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

查看:328
本文介绍了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\n", 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\n", mystruct, mystruct->foo);
    mystruct = func1(mystruct);
    printf("back in func2: %p\n", 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?

推荐答案

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

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

默认情况下,所有返回值均为int.因此,如果缺少函数原型,则编译器会将返回值视为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天全站免登陆