3
#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?

Mysticial
  • 464,885
  • 45
  • 335
  • 332
Angus
  • 12,133
  • 29
  • 96
  • 151

3 Answers3

6

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?

Community
  • 1
  • 1
Mysticial
  • 464,885
  • 45
  • 335
  • 332
4

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.

Man of One Way
  • 3,904
  • 1
  • 26
  • 41
  • This is not correct. Return code is NOT DEFINED in this case. But in most case return value stored in register. So exit from main preserve old value of returning value (register) of the printf. – Dmitry Poroh Jul 13 '12 at 09:01
  • You mean the `printf` value is incidentally stored in `%rax` (on x86 for example) and that's why it returns `2` in this case? – Man of One Way Jul 13 '12 at 09:03
-1

There is problem in your memcpy statement.

1) You should pass pointer to your array in stead you are passing pointer to pointer of
your array.

2) You should pass size of your array, sizeof(a) will return only size of int so u have to multiply it with max index of array.

You have to do little modification in your code as given below,

memcpy(b, a, sizeof(a) * 4);

Kinjal Patel
  • 405
  • 2
  • 7