WebAssembly / wabt

The WebAssembly Binary Toolkit
Apache License 2.0
6.9k stars 702 forks source link

Will uninitialized local var be optimised? #2473

Closed Chocolatieee0929 closed 2 months ago

Chocolatieee0929 commented 2 months ago

When I was trying to write EOS contract, which use wasm to compilered, I found that uninitialized local var seem to be optimised. For example, the result, when added to any number and uninitialized local variable a1, is printed as zero. The test code as follows:

#include <eosio/eosio.hpp>

using namespace eosio;
using namespace std;

CONTRACT testUninitializd : public contract {
    public:
        using eosio::contract::contract;

        ACTION add1() {
            uint64_t a1;
            for (uint64_t i = 0; i < 5; i++){
                a1 += i;
                print_f("%:% ", i, a1);
            }
        }

        ACTION add2() {
            uint64_t b1 = 10;
            for (uint64_t i = 0; i < 5; i++){
                b1 += i;
                print_f("%:% ", i, b1);
            }
        }
};

test result :

  testUninitializd
add a1 0:0 1:0 2:0 3:0 4:0 
add b1 0:10 1:11 2:13 3:16 4:20 

The compiled data as follows indicates that there is a local.get operation without any accompanying store operation. 1727178422028 Please tell me if my thought is right, thks

SoniEx2 commented 2 months ago

please check your compiler's documentation, this is not a wabt issue.

rossberg commented 2 months ago

Using an uninitialised variable is Undefined Behaviour in C/C++, and the C compiler is licensed to do whatever it wants, including launching missiles. This is unrelated to Wasm.

Chocolatieee0929 commented 2 months ago

Thanks for your answer.