This is the mail archive of the
libffi-discuss@sourceware.org
mailing list for the libffi project.
Re: return value buffer malloc()'ed vs alloca()'ed
- From: Anthony Green <green at moxielogic dot com>
- To: Igor Bogomazov <ygrex at ygrex dot ru>
- Cc: "libffi-discuss at sourceware dot org" <libffi-discuss at sourceware dot org>
- Date: Tue, 8 Oct 2013 13:30:21 -0400
- Subject: Re: return value buffer malloc()'ed vs alloca()'ed
- Authentication-results: sourceware.org; auth=none
- References: <20131008101354 dot 43baeeeb at ygrex-mac>
Igor,
You've hit one of the oddities of the libffi API. The result
buffer needs to be the largest native integral type on your system.
Use a 64 bit long for rc instead of mallocing the exact return type
size. You can pass it into ffi_call as &rc and simply cast it to an
int at the end. I just checked the docs and it's definitely not
clear. I'll fix this. libffi is just a tiny bit faster when it can
make this size assumption, but I agree that it isn't pretty.
AG
On Tue, Oct 8, 2013 at 1:13 PM, Igor Bogomazov <ygrex@ygrex.ru> wrote:
> Hello,
>
> I've been trying to investigate valgrind warnings for a while and found
> an undocumented feature, please let me know if it is well-known.
>
> What I did.
>
> I modified a code given in «2.2 Simple Example» so that return value
> (rc), originally declared as (int), became an (int *)malloc(sizeof(int))
> so that it is resident in heap since that. Of cource, (&rc) replaced
> with (rc) later in the code.
>
> What I get.
>
> valgrind complaints about «Invalid write of size 8» while «Address
> 0x55ec040 is 0 bytes inside a block of size 4 alloc'd», it is exactly
> that allocated (rc) buffer.
>
> Notes.
>
> Allocating buffer for the return value using alloca() does the trick and
> makes valgrind silent.
>
> Further.
>
> I looked at x86/unix64.S, it is exactly the line:
> movq %rax, (%rdi)
> that causes the valgrind's warning (at .Lst_uint32)
>
> That is my question: is it necessary to allocate a buffer for the return
> value with alloca() and never with malloc()?
>
> --
> Sincerely yours,
>
> Igor Bogomazov
>