I think I just made wrong offset to get the section.
Your program iterates over all sections, so at the end of the first loop, sectHdr contains the section header of the last section, which is unlikely to the .text section.
So in the second loop you print the contents of whatever section happened to be the last.
To print the .text section, you need to save its section header when you come across it.
Update:
So if I do for loop over all sections and then strcmp with every name, and when I find matching with .text I save the adress of that header.
You don't save the address of that header -- you save the contents.
What about if I want to access to Symbol table, which is not Section (has its own type: Elf32_Sym), how do I reach that table?
The symbol table does have its own section (containing a set of Elf32_Sym records). See this answer.
Update 2:
This code:
if(strcmp(name, ".symtab") == 0) {
//symbolTable = (Elf32_Sym*)sectHdr.sh_addr;
symtab = (Elf32_Shdr*) §Hdr;
}
if(strcmp(name, ".strtab") == 0) {
strtab = (Elf32_Shdr *) §Hdr;
}
is obviously broken: you save a pointer to memory that you overwrite on each iteration of the loop. You must save a copy of .symtab and .strtab section header (just as you do for .text).
An even better solution is to mmap the entire file into memory. Then you can save pointers to various parts of it (that's what the other answer does -- the data there points to the start of mmaped region).