0

I have a 'runtime error' when I try to copy the value of the variable 'b' into the variable 'a'.

#include <stdio.h>
#include <string.h>

typedef struct{
        unsigned short a;
}st1;

main()
{
        st1* myStruct;
        unsigned short b = 0xFFFF;

        memcpy(&myStruct->a, &b,sizeof(b));
}

I would like to know why it happens. Any help would be appreciated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Note that using `memcpy()` to copy an `unsigned short` is taking a sledgehammer to crack a nut. Writing `myStruct->a = b;` would do the same job (only quicker and clearer), and would create the same havoc while `myStruct` is an uninitialized pointer. – Jonathan Leffler Mar 20 '13 at 01:04

1 Answers1

1

Because you did not allocate memory for myStruct. You didn't initialize it, so its value is some random value during memcpy(). Thus, &myStruct->a is accessing some random address, and writing to &myStruct->a is likely to lead to runtime error.

timrau
  • 22,578
  • 4
  • 51
  • 64