Arista Networks Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
I'd rather copy paste the info here:
From gdb backtrace, seems that printf("%s\n", x) is being silently converted into puts(x) which is fine except when x is NULL, where printf shows (null) but puts() segfaults.
Changing the string, or using the return value avoids this "optimization".
Changing the optimization level -O doesn't affect it.
It is caused by GCC optimization.
(gdb) disassemble main
Dump of assembler code for function main:
0x0000000000400544 <+0>: push %rbp
0x0000000000400545 <+1>: mov %rsp,%rbp
0x0000000000400548 <+4>: mov $0x40065c,%eax
0x000000000040054d <+9>: mov $0x0,%esi
0x0000000000400552 <+14>: mov %rax,%rdi
0x0000000000400555 <+17>: mov $0x0,%eax
0x000000000040055a <+22>: callq 0x400440 <printf@plt>
0x000000000040055f <+27>: mov $0x0,%edi
0x0000000000400564 <+32>: callq 0x400430 <puts@plt>
0x0000000000400569 <+37>: mov $0x0,%eax
0x000000000040056e <+42>: pop %rbp
0x000000000040056f <+43>: retq
End of assembler dump.
(gdb)
Works perfectly fine on linux too.
machine:~/cfiles > ./a.out
test (null)
test (null)
machine:~/cfiles > vi NULL.c
machine:~/cfiles > gcc NULL.c
machine:~/cfiles > ./a.out
test (null)
test (null)
(null)
(null)
machine:~/cfiles > vi NULL.c
machine:~/cfiles > gcc NULL.c
machine:~/cfiles > ./a.out
(null)
(null)
machine:~/cfiles >
Works perfectly fine on linux too.
machine:~/cfiles > ./a.out
test (null)
test (null)
machine:~/cfiles > vi NULL.c
machine:~/cfiles > gcc NULL.c
machine:~/cfiles > ./a.out
test (null)
test (null)
(null)
(null)
machine:~/cfiles > vi NULL.c
machine:~/cfiles > gcc NULL.c
machine:~/cfiles > ./a.out
(null)
(null)
machine:~/cfiles >
I'm getting a segmentation fault when i try to run the second part. I'm using gcc version 4.5.3 (GCC). I think it is due to "format ‘%s’ expects type ‘char *’, but argument has type ‘void *’ " refer to bugs.centos.org/view.php?id=4128
- anirudh March 05, 2012