Jan 1, 2019

[C++][C] The case of forgotten return bug

read: https://yurichev.com/blog/no_return/

Scenarios:
  • Even without return variable from a function signature which returns, %rax is filled with
    something due to compiler will use as less registers as possible.
    Since %rax is filled with something which is not the returning value, this issues a bug
    (in debug/none-optimized mode).
  • While in optimization mode, optimize prevails, thus a function with signature which returns but inside the function body has no return statement, compiler opts out with returning 0, which again, issues a bug.


Take away:
  • Always turns on -Wall during the programming(I'm using Vim) and compiling.
  • In C++17, consider using attribute: [[nodiscard]] a good practice.
    For side-effect only, take Discarded-value expressions into consideration.


#include <stdio.h>
#include <stdlib.h>

struct color
{
        int R;
        int G;
        int B;
};

struct color* create_color (int R, int G, int B)
{
        struct color* rt=(struct color*)malloc(sizeof(struct color));
        rt->R=R;
        rt->G=G;
        rt->B=B;
        // must be "return rt;" here
};

int main()
{
        struct color* a=create_color(1,2,3);
        printf ("%d %d %d\n", a->R, a->G, a->B);
};

https://godbolt.org/z/o8bgyD
create_color(int, int, int):
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
movl %edi, -20(%rbp)
movl %esi, -24(%rbp)
movl %edx, -28(%rbp)
movl $12, %edi
call malloc
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movl -20(%rbp), %edx
movl %edx, (%rax)
movq -8(%rbp), %rax
movl -24(%rbp), %edx
movl %edx, 4(%rax)
movq -8(%rbp), %rax
movl -28(%rbp), %edx
movl %edx, 8(%rax)
nop
leave
ret
.LC0:
.string "%d %d %d\n"
main:
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movl $3, %edx
movl $2, %esi
movl $1, %edi
call create_color(int, int, int)
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movl 8(%rax), %ecx
movq -8(%rbp), %rax
movl 4(%rax), %edx
movq -8(%rbp), %rax
movl (%rax), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movl $0, %eax
leave
ret

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.