-1

I want to copy some part of data into source_mac

This is my code:

uint8_t *data
uint8_t *source_mac

memcpy(&source_mac, &data[6], 6);

So I want to copy 6 bytes from data, starting with the 6th byte in data, into source_mac... What am I doing wrong?

4
  • 1
    Does your compiler complain about passing wrong type of argument for the destination? If you get and error or warning, show the exact and complete message in your question. Commented Dec 10, 2023 at 11:49
  • 1
    &source_mac this is the address of the pointer variable, not where it points to. Use source_mac or &source_mac[0] Commented Dec 10, 2023 at 11:52
  • Your pointer are uninitialized, so your memcpy call tries to copy 6 bytes from some random location (&data[6]) to wherever the source_mac variable is located (which depends scope, which is unclear from your incomplete code example). Even if data was properly initialized, passing &source_mac to memcpy overwrites the source_mac variable, not what it (should) point to. Commented Dec 10, 2023 at 11:59
  • You are asking for help for a function that is described on every CPP webpage. The first parameter is always the destination, never the source. And you are accessing to unallocated memory. Commented Dec 11, 2023 at 18:52

1 Answer 1

2

There are multiple problems in your code fragment:

  • the 6th byte is data[5]
  • you pass &source_mac as the destination, which is the address of the source_mac pointer, not the address of the destination array. You should either pass &source_mac[0] or simply source_mac

Here is a modified version:

void my_function(uint8_t *data, uint8_t *source_mac) {
    [...]
    memcpy(source_mac, &data[5], 6);
    [...]
Sign up to request clarification or add additional context in comments.

2 Comments

I always get an segmentation fault, when i use the code you provided
@hannah: I did not provide a full program, can you post the source to the program that causes a segmentation fault? Add an EDIT paragraph at the end of your question and post the code surrounded by ``` quotation marks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.