简体   繁体   中英

Copying unsigned char in C

I want to use memcpy but it seems to me that it's copying the array from the start?

I wish to copy from A[a] to A[b] . So, instead I found an alternative way,

void copy_file(char* from, int offset, int bytes, char* to) {
    int i;
    int j = 0;
    for (i = offset; i <= (offset+bytes); i++) to[i] = from[j++];
}

I'm getting seg faults but I don't know where I am getting this seg fault from? each entry holds 8 bytes so my second attempt was

void copy_file(char* from, int offset, int bytes, char* to) {
    int i;
    int j = 0;
    for (i = 8*offset; i <= 8*(offset+bytes); i++) to[i] = from[j++];
}

but still seg fault. If you need more information please don't hesitate to ask!

I'm getting seg faults but I don't know where I am getting this seg fault from?

Primary Suggestion: Learn to use a debugger. It provides helpful information about erroneous instruction(s).


To answer you query on the code snippet shown on above question,

  1. Check the incoming pointers ( to and from ) against NULL before dereferencing them.
  2. Put a check on the boundary limits for indexes used. Currently they can overrun the allocated memory.

To use memcpy() properly:

as per the man page , the signature of memcpy() indicates

void *memcpy(void *dest, const void *src, size_t n);

it copies n bytes from address pointer by src to address pointed by dest .

Also, a very very important point to note:

The memory areas must not overlap.

So, to copy A[a] to A[b], you may write something like

memcpy(destbuf, &A[a], (b-a) );

it seems to me that memcpy copying the array from the start

No, it does not. In fact, memcpy does not have a slightest idea that it is copying from or to an array. It treats its arguments as pointers to unstructured memory blocks.

If you wish to copy from A[a] to A[b] , pass an address of A[a] and the number of bytes between A[b] and A[a] to memcpy , like this:

memcpy(Dest, &A[a], (b-a) * sizeof(A[0]));

This would copy the content of A from index a , inclusive, to index b , exclusive, into a memory block pointed to by Dest . If you wish to apply an offset to Dest as well, use &Dest[d] for the first parameter. Multiplication by sizeof is necessary for arrays of types other than char , signed or unsigned.

Change the last line from

for (i = offset; i <= (offset+bytes); i++)
to[i] = from[j++];

to

for (i = offset; i <= bytes; i++,j++)
to[j] = from[i];

This works fine for me. I have considered offset as the start of the array and byte as the end of the array. ie to copy from[offset] to from[bytes] to to[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM