nibblebits / PeachCompiler

A C compiler created for the how to create a C Compiler online course
GNU General Public License v2.0
76 stars 33 forks source link

I found an issue when I call printf to output values of array items. #18

Open zzdmfk opened 6 months ago

zzdmfk commented 6 months ago

printf outputs addresses of array items, not values. Have you got a schedule to fix issues?

C code:

int printf(const char* str, ...);

int main() { int i; int arr[3]; arr[0] = 5; arr[1] = 6; arr[2] = 7;

for(i = 0; i < 3; i++) printf("%d\n", arr[i]);

return 0; }

Asm code:

george@george-ubuntu:~/Desktop/gitcompiler/PeachCompiler$ ./main section .data section .text extern printf global main ; main function main: push ebp mov ebp, esp sub esp, 16 push dword 5 pop eax mov dword [ebp-16], eax push dword 6 pop eax mov dword [ebp-12], eax push dword 7 pop eax mov dword [ebp-8], eax push dword 0 pop eax mov dword [ebp-4], eax jmp .for_loop1 .entry_point_3: push dword [ebp-4] pop eax push eax inc eax push eax pop eax mov dword [ebp-4], eax pop eax .for_loop1: push dword [ebp-4] push dword 3 pop ecx pop eax cmp eax, ecx setl al movzx eax, al push eax pop eax cmp eax, 0 je .for_loop_end2 lea ebx, [printf] push ebx pop ebx mov dword [function_call_5], ebx lea ebx, [ebp-16] push ebx pop ebx push dword [ebp-4] pop eax imul eax, 4 add ebx, eax push ebx pop eax push eax mov eax, str_6 push eax call [function_call_5] add esp, 8 push eax pop eax push eax add esp, 4 push dword [ebp-4] pop eax push eax inc eax push eax pop eax mov dword [ebp-4], eax pop eax jmp .for_loop1 .for_loop_end2: .exit_point_4: push dword 0 pop eax add esp, 16 pop ebp ret add esp, 16 pop ebp ret section .data function_call_5: dd 0 section .rodata str_6: db '%', 'd', 10, 0 everything compiled file /usr/bin/ld: ./test.o: warning: relocation in read-only section `.text' /usr/bin/ld: warning: creating DT_TEXTREL in a PIE nasm -f elf32 ./test -o ./test.o && gcc -m32 ./test.o -o ./test

Outputs:

george@george-ubuntu:~/Desktop/gitcompiler/PeachCompiler$ ./test -2215688 -2215684 -2215680 `

zzdmfk commented 6 months ago

I simplified C code like below, the problem still persists. It seems that the brackets can only contain numbers.

int printf(const char* str, ...);

int main() { int i = 2; int arr[3]; arr[0] = 5; arr[1] = 6; arr[2] = 7;

printf("%d\n", arr[i]);

return 0; }