Thursday, January 12, 2023

C++: Using non-standard data types

When you use non-standard data types like enum, bool, double, long double, it might become a problem if you are sending data to another platform, e.g. sending from x86 to ARM, or even when sending from Windows to Linux. For example, long double is 8 bytes in MSVC but 16 bytes in GCC. These size differences will result in errors when casting the received bytes to data. Always know non-standard data type lengths of the platform that you are communicating with.

Wednesday, January 11, 2023

C++: Simple serialization

Simple serialization demo by converting struct to char (byte) array:

//C++ simple serialization demo, converting struct to char (byte) array and back.
//Şamil Korkmaz, January 2023
#include <iostream>
#include <string.h> //for memcpy
typedef struct {
int d;
int i;
} MY_DATA;
void f(char* pData) {
//print individual bytes (2 ints = 4+4 = 8 bytes):
for (int i=0; i < sizeof(MY_DATA); i++) printf("%x ", pData[i]);
printf("\n");
//copy bytes to MY_DATA type:
MY_DATA data2;
memcpy(&data2, pData, sizeof(MY_DATA)); //copying to data2 causes contents of memory pointed to by pData to be interpreted as MY_DATA
std::cout <<"data2.d = " << data2.d << std::endl;
std::cout <<"data2.i = " << data2.i << std::endl;
pData[1] = 1; //changing second byte from 0 to 1 adds 2^8 = 256 to d value
}
int main() {
MY_DATA data; data.d = 5; data.i = 3;
f((char*)&data); //interpret contents of memory pointed to by &data as char
std::cout <<"data.d = " << data.d << std::endl;
return 0;
}

Monday, January 9, 2023

C: char pointer vs array

In C, the difference between a char pointer and char array becomes clear when you want to do assignment:

  #include<stdio.h>
  #include<string.h> //for strcpy
  int main() {
      char s[][10] = {"aaa", "bbb", "ccc"};
      //char* s[] = {"aaa", "bbb", "ccc"}; //same as above
      char* t1 = s[1];
      char t2[10]; strcpy(t2, s[1]);
      //t2 = s[1];// error: assignment to expression with array type
      printf("s[1] = %s\n", s[1]);
      printf("t1 = %s\n", t1);
      printf("t2 = %s\n", t2);
      return 0;
  }

s[1] is a char pointer. You can assign a char pointer to another char pointer but you cannot assign a char array to char pointer, you have to use strcpy. 

Another interesting difference:

    char a[] = "string1"; 
    char *p1  = a;
    char *p2  = "string2";
    a[0] = 'z';
    printf("a[0] = %c\n", a[0]);
    p1[0] = 'k'; //works fine, changes a[0]
    printf("a[0] = %c\n", a[0]);
    p2[0] = 'm'; //results in segmentation fault
    printf("p2[0] = %c\n", p2[0]);