10. Structures

A structure groups different types of data together; each element of the structure is called a member. The structure members are accessed using constant offsets. To understand the concept, take a look at the following C program. The simpleStruct definition contains three member variables (ab, and c) of different data types. The main function defines the structure variable (test_stru) at ➊, and the address of the structure variable (&test_stru) is passed as the first argument at ➋ to the update function. Inside of the update function, the member variables are assigned values:

struct simpleStruct
{
int a;
short int b;
char c;
};

void update(struct simpleStruct *test_stru_ptr) {
test_stru_ptr->a = 6;
test_stru_ptr->b = 7;
test_stru_ptr->c = 'A';
}

int main()
{
struct simpleStruct test_stru; ➊
update(&test_stru); ➋
return 0;
}

In order to understand how the members of the structures are accessed, let's look at the disassembled output of the update function. At ➌, the base address of the structure is moved into the eax register (remember, ebp+8 represents the first argument; in our case, the first argument contains the base address of the structure). At this stage, eax contains the base address of the structure. At ➍, the integer value 6 is assigned to the first member by adding the offset 0 to the base address ([eax+0] which is the same as [eax]). Because the integer occupies 4 bytes, notice at ➎ the short int value 7 (in cx) is assigned to the second member by adding the offset 4 to the base address. Similarly, the value 41h (A) is assigned to the third member by adding 6 to the base address at ➏:

push ebp
mov ebp, esp
mov eax, [ebp+8] ➌
mov dword ptr [eax], 6 ➍
mov ecx, 7
mov [eax+4], cx ➎
mov byte ptr [eax+6], 41h ➏
mov esp,ebp
pop ebp
ret

From the preceding example, it can be seen that each member of the structure has its own offset and is accessed by adding the constant offset to the base address; so, the general form can be written as follows:

[base_address + constant_offset]

Structures may look very similar to arrays in the memory, but you need to remember a few points to distinguish between them:

  • Array elements always have the same data types, whereas structures need not have the same data types.
  • Array elements are mostly accessed by a variable offset from the base address (such as [eax + ebx] or [eax+ebx*4]), whereas structures are mostly accessed using constant offsets from the base address (for example, [eax+4]).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.95.38