How does pointer comparison work in C? Is it ok to compare pointers that don’t point to the same array?

According to the C11 standard, the relational operators <, <=, >, and >= may only be used on pointers to elements of the same array or struct object. This is spelled out in section 6.5.8p5: When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed … Read more

Virtual tables and memory layout in multiple virtual inheritance

Virtual bases are very different from ordinary bases. Remember that “virtual” means “determined at runtime” — thus the entire base subobject must be determined at runtime. Imagine that you are getting a B & x reference, and you are tasked to find the A::a member. If the inheritance were real, then B has a superclass … Read more

Finding the address range of the data segment

If you’re working on Windows, then there are Windows API that would help you. //store the base address the loaded Module dllImageBase = (char*)hModule; //suppose hModule is the handle to the loaded Module (.exe or .dll) //get the address of NT Header IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(hModule); //after Nt headers comes the table of section, so … Read more

Are C-structs with the same members types guaranteed to have the same layout in memory?

Are C-structs with the same members types guaranteed to have the same layout in memory? Almost yes. Close enough for me. From n1516, Section 6.5.2.3, paragraph 6: … if a union contains several structures that share a common initial sequence …, and if the union object currently contains one of these structures, it is permitted … Read more

Struct memory layout in C

It’s implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is: Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added before each struct member, to ensure correct alignment. Each primitive type T … Read more