I have the following C program:
#include <stdio.h>
int main() {
int i = 0;
int N = 10;
while(i < N) {
printf("counting to %d: %d", N, i);
//i = i 1;
}
return 0;
}
I would like to compile this first to assembly, then to binary for instructional purposes. So, I issue the following commands:
$ gcc -S count.c -o count.s
$ as -o count.o count.s
$ ld -o count -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib/x86_64-linux-gnu/libc.so count.o -lc
These compile the C to assembly, assemble the assembly to binary, and then link the library containing the printf
function, respectively.
This works. Output:
counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0
etc until I ctrl-c the program.
However, when I uncomment the i = i 1
line:
Segmentation fault (core dumped)
What is going wrong here?
UPDATE: Here is count.s
(with the i = i 1
line included)
.file "count.c"
.text
.section .rodata
.LC0:
.string "counting to %d: %d"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $0, -8(%rbp)
movl $10, -4(%rbp)
jmp .L2
.L3:
movl -8(%rbp),