Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying datas into the array using memcpy

Tags:

c

#include <stdio.h>

int main(){
    int a[4];
    int b[4],i;
    a[0] = 4;
    a[1] = 3;
    a[2] = 2;
    a[3] = 1;
    memcpy(&b, &a, sizeof(a));
    for (i = 0; i < 4; i++){
        printf("b[%d]:%d",i,b[i]);
    }
    printf("%d",sizeof(b));
}

ANS:

b[0]:4b[1]:3b[2]:2b[3]:116
Exited: ExitFailure 2

I'm getting the correct answers. But getting a exception as Exited: ExitFailure 2.

Is this way of copying the array datas using memcpy is wrong?

like image 491
Angus Avatar asked Jul 31 '26 19:07

Angus


2 Answers

Try adding a return 0; at the end of main().

Omitting the return value is probably causing the function to return stack garbage. (that's not 0)

The test app/script is therefore complaining of failure when it sees a non-zero return value.


Prior to C99, omitting the return statement is technically undefined behavior. Starting from C99, it will default to 0 if it is omitted.

More details here: Why main does not return 0 here?

like image 163
Mysticial Avatar answered Aug 02 '26 10:08

Mysticial


Correction:

Not explicitly returning 0 (return 0;) leads to undefined behaviour prior to C99.

However, since a particular register is usually used for storing a return value (for example eax in x86) from a function, the value in that register is returned.

It just happen to be that printf("%d",sizeof(b)); is storing the size of the char array in the same register that is used for returning a value from a function.

Because of this, the returned value is 2.

Original answer:

Since you do not state return 0; at the end of main, the last printf call is interpreted as the return value of main.

sizeof(b) returns 16 which is 2 characters long, thus the program returns 2 as exit code.

like image 25
Man of One Way Avatar answered Aug 02 '26 12:08

Man of One Way



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!