GCC如何保证C语言字符串以'\0'结尾?
int main(){
char a[9]="abcdef";
}
然后部分反汇编是这样的
080483cd <main>:
80483cd: 55 push %ebp
80483ce: 89 e5 mov %esp,%ebp
80483d0: 83 ec 10 sub $0x10,%esp
80483d3: c7 45 f7 61 62 63 64 movl $0x64636261,-0x9(%ebp)
80483da: c7 45 fb 65 66 00 00 movl $0x6665,-0x5(%ebp)
80483e1: c6 45 ff 00 movb $0x0,-0x1(%ebp)
80483e5: c9 leave
80483e6: c3 ret
80483e7: 66 90 xchg %ax,%ax
80483e9: 66 90 xchg %ax,%ax
80483eb: 66 90 xchg %ax,%ax
80483ed: 66 90 xchg %ax,%ax
80483ef: 90 nop
我就想问问,为什么0x80483e1地址处是movb $0x0,-0x1(%ebp)字符串共6个字符,就是要填上7个字节数据,那么从-0x9(%ebp)开始填,不是应该在-0x3(%ebp)填上0x0吗?但为什么GCC要在-0x1(%ebp)填上0x0?这样填怎么能保证字符串是以0结尾的?
------解决方案--------------------字符串总6字节,a是个数组,剩余部分都被填成0,a[6]至a[8]都是0
定义数组时,若只对数组部分元素赋初值,其他元素全被赋为0
80483d3: c7 45 f7 61 62 63 64 movl $0x64636261,-0x9(%ebp) 将abcd'放入%ebp-0x9,%ebp-0x8,%ebp-0x7,%ebp-0x6
80483da: c7 45 fb 65 66 00 00 movl $0x6665,-0x5(%ebp) 将ef00放入%ebp-0x5,%ebp-0x4,%ebp-0x3,%ebp-0x2
80483e1: c6 45 ff 00 movb $0x0,-0x1(%ebp) 将0放入%ebp-0x1
movl long四个字节,movb byte1个字节。a[9]共9字节,两次movl,一次movb