My program/process exited abnormally? I doubt something is wrong with the following code:
There are two typedef TYPE1, TYPE2. (TYPE1’s size is bigger than TYPE2)
TYPE1 var1;
TYPE2 var2;
....
....var2 has been assigned.
....
memset(&var1, 0, sizeof(var1));
memcpy(&var1, (TYPE1 *)&var2, sizeof(TYPE1));
printf("....");
-
Cast var2 may cause accessing the illegal memory which may lead to segmentation fault? I thought it may mess up the data following the var2 in memory, but cannot make segmentation fault? I found my program exit here, since the following printf() did not print anything.
-
Cast will ruin the data following var2 in memory even if it is only read (var2 is just source of memcpy().
-
what happens if I change it like memcpy(&var1, (TYPE1 *)&var2, sizeof(TYPE2));
Thanks.
So first: you don’t need to cast
&var2toTYPE1*when usingmemcpy.memcpyexpectsvoid*, and any pointer type can be cast tovoid*.The problem here is, when
TYPE1is bigger thanTYPE2and you are copying the data fromvar2tovar1usingsizeof(TYPE1)as the size, memcpy will eventually read from beyond the memory occupied byvar2. As a consequence, you are accessing memory you are not allowed to access. Hence, a segmentation fault is the best you could have gotten there, since that error might also have be gone unnoticed for quite some time until it really could have caused trouble (undefined behavior is the key phrase here).When you copy only
sizeof(TYPE2)bytes fromvar2tovar1, you are ok in terms of memory access (as long asTYPE1is really bigger thanTYPE2).