On Wednesday, 1 February 2017 at 10:05:49 UTC, 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];

clang (version 3.8.1) failed to find error in this code.

You have to define the mymemcpy() in another source file and only put the prototype in this module. If the compiler sees the code it can do the complete data flow analyses. With only the declaration it can't and that is Walter's point. The annotations allow to give to the declaration the information the compiler can not deduce itself from the code, because the code is in another module (object file, library).

Reply via email to