memcpy() comparison: C, Rust, and D
Walter Bright via Digitalmars-d
digitalmars-d at puremagic.com
Wed Feb 1 12:58:08 PST 2017
On 2/1/2017 2:05 AM, Richard Delorme wrote:
> On Tuesday, 31 January 2017 at 23:30:04 UTC, Walter Bright wrote:
>> On 1/31/2017 3:00 PM, Richard Delorme wrote:
>> The thing about memcpy is compilers build in a LOT of information about it
>> that simply is not there in the declaration. I suggest retrying your example
>> for gcc/clang, but use your own memcpy, i.e.:
>>
>> void* mymemcpy(void * restrict s1, const void * restrict s2, size_t n);
>>
>> Let us know what the results are!
>
> //-----8<-------------------------------------------------------
> #include <string.h>
> #include <stdio.h>
>
> void* mymemcpy(void* restrict dest, const void* restrict src, size_t n) {
> const char *s = src;
> char *d = dest;
> for (size_t i = 0; i < n; ++i) d[i] = s[i];
> return d;
> }
>
> void *copy(const void *c, size_t n) {
> char d[16];
> return mymemcpy(d, c, n);
> }
>
> int main(void) {
> char a[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
> char *b = copy(a, 8);
>
> for (int i = 0; i < 16; ++i) printf("%d ", b[i]);
> putchar('\n');
> }
> //-----8<-------------------------------------------------------
> $ gcc mymemcpy.c -O2 -W
> mymemcpy.c: In function 'copy':
> mymemcpy.c:13:9: warning: function returns address of local variable
> [-Wreturn-local-addr]
> return mymemcpy(d, c, n);
> ^~~~~~~~~~~~~~~~~
> memcpy4.c:12:7: note: declared here
> char d[16];
Note that you included the source code for mymemcpy(). gcc is apparently able to
examine the source code to determine that 'd' is returned. Please try it just
using the declaration.
More information about the Digitalmars-d
mailing list