错误:函数'memcpy_s'的隐式声明;您是指“memcpy”吗?[-Werror=隐式函数声明]

watbbzwu  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(295)

I am trying to make a memcpy_s() call. Below is my code snippet where I am observing warning " error: implicit declaration of function ‘memcpy_s’; did you mean ‘memcpy’? [-Werror=implicit-function-declaration]"

#include <stdio.h>
#include <string.h>
#include <stdint.h>

static const uint32_t ab[10] = {0,1,2,3,4,5,6,7,8,9};
void main()
{
  uint32_t u[10];
  memcpy_s((void *)&u[0], sizeof(u), (void *)&ab[0], 10 * sizeof(uint32_t));
  
}
yhxst69z

yhxst69z1#

It appears that the IDE/Platform you are using doesn't support the memcpy_s() variant of memcpy , which IMO is good! I'd recommend using memcpy() instead.

If you haven't already used it before --

Looking at the reference page for memcpy
void *memcpy(void *restrict dest, const void *restrict src, size_t n);
It needs the following arguments:

dest - pointer to the object to copy to
src - pointer to the object to copy from
n - number of bytes to copy

So,

memcpy((void*)&u[0], (void*)&ab[0], 10*sizeof(uint32_t));

Or better,

memcpy((void*)&u[0], (void*)&ab[0], COUNT_OF(ab)*sizeof(uint32_t));
//                                  ↑ Note this!

with a minimalistic, not-so-perfect macro to get count of elements in the array:

#define COUNT_OF(var)   (sizeof(var)/sizeof(var[0]))

By the way, there is a typo in your code:

memcpy_s(void *)&u[0], sizeof(u), (void*)&ab[0], 10*sizeof(uint32_t));
//      ↑      ↑ ouch!

is the parenthesis. If you at all migrate to a platform where you have memcpy_s() supported then change it to:

memcpy_s((void*)&u[0], sizeof(u), (void*)&ab[0], COUNT_OF(ab)*sizeof(uint32_t));

Update:
I learnt from OP that the actual assignment is to write a function which behaves like memcpy() . Assuming the nature of arguments to remain consistent with what memcpy() needs, adding a return to indicate if the copy happened successfully, you can of course add more.
A bare-minimum, simple version can be programmed as:

int my_memcpy(void *pDest, void *pSrc, size_t sz)
{
    char *src = (char *)pSrc;   // Or use uint8_t instead of char
    char *dest = (char *)pDest; // Or use uint8_t instead of char
    
    // Validate pointers to avoid seg-faults
    if(NULL == pDest || NULL == pSrc) {
        return -1;
    }
        
    // Copy contents
    for (int i = 0; i < sz; i++) {
        dest[i] = src[i];
    }
    return 0;
}

相关问题