memcpy
Function Usage
Copy data of a specified length from the source memory to the destination memory.
Function Syntax
void *memcpy(void * destination, const void *source, size_t size);
Parameters
Parameter |
Description |
Value Range |
Input/Output |
|---|---|---|---|
destination |
Pointer to the destination memory used to store the copied data. |
The value cannot be NULL. |
Output |
source |
Pointer to the source memory from which data is to be copied. |
The value cannot be NULL. |
Input |
size |
Number of copied bytes. |
The value cannot be negative. |
Input |
Return Value
- Success: A pointer to the destination memory is returned.
- Failure: A null pointer is returned.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "kqmalloc.h" #define KQMALLOC_TEST_LEN 10 void MemcpyExample() { int8_t *source = (int8_t *)malloc(KQMALLOC_TEST_LEN * sizeof(int8_t)); if (source == NULL) { printf("source is null\n"); return; } else { printf("source address: %lx\n", source); for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) { source[i] = i; } printf("source test data:"); for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) { printf(" %d", source[i]); } printf("\n"); } int8_t *destination = (int8_t *)malloc(KQMALLOC_TEST_LEN * sizeof(int8_t)); if (destination == NULL) { printf("destination is null\n"); free(source); return; } else { printf("destination address: %lx\n", destination); printf("destination test data before memcpy:"); for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) { printf(" %d", destination[i]); } printf("\n"); } int8_t *res = (int8_t *)memcpy(destination , source, KQMALLOC_TEST_LEN * sizeof(int8_t)); printf("res address: %lx\n", res); if (res != NULL) { printf("res test data after memcpy:"); for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) { printf(" %d", res[i]); } printf("\n"); } free(source); free(destination); } int main(void) { MemcpyExample(); return 0; } |
Perform the compilation.
1 | gcc run_your_application.c -o run_your_application -I/usr/local/ksl/include -L/usr/local/ksl/lib |
Run your application.
1 | LD_PRELOAD=/usr/local/ksl/lib/libkqmalloc.so ./run_your_application |
Output:
1 2 3 4 5 6 | source address: ffffbb202174 source test data: 0 1 2 3 4 5 6 7 8 9 destination address: ffffbb202168 destination test data before memcpy: 92 33 32 -69 -1 -1 0 0 0 0 res address: ffffbb202168 res test data after memcpy: 0 1 2 3 4 5 6 7 8 9 |
Parent topic: Function Syntax