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.
Because you did not allocate memory for
myStruct. You didn’t initialize it, so its value is some random value duringmemcpy(). Thus,&myStruct->ais accessing some random address, and writing to&myStruct->ais likely to lead to runtime error.