Waterfall_11
Waterfall_11

Reputation: 11

C++ pointers were unexpected increased while were watched in debugging but fine while run

Ubuntu 20.04.6 g++-9 (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0

I written following C++ code in vs code and debug.

// main.cpp
#include "crc.h"

#include <cstdint>
#include <iostream>
#include <vector>

int main() {
    int size;
    unsigned char *bytes = new unsigned char[20];
    for (int i = 0; i < 16; ++i)
    {
        *(bytes + i) = i;
    }
    size = 16;
    unit16_t crc_value = crc(bytes, size);
    std::cout << "crc: " << std::hex << crc_value << std::endl;
    return 0;
}
// crc.h
#include <cstdint>

uint16_t crc(const unsigned char*, const int);
// crc.cpp
#include <cstdint>
#include <iostream>

uint16_t crc(const unsigned char *ptr, const int count)
{
    uint16_t crc = 0;
    for (int i = 0; i < count; ++i)  //Iterate over every byte in *ptr
    {
        crc = crc ^ (static_cast<uint16_t>(*(ptr + i)) << 8);  //Byte from *ptr ^ with crc

        for (int bit = 0; bit < 8; ++bit)  //Iterate over every bit in crc
        {
            if (crc & 0x8000)  //The highest bit is 1
                crc = (crc << 1) ^ 0x1021;
            else
                crc = crc << 1;
        }
        std::cout << i << " crc: " << std::hex << crc << std::endl;
    }
    return crc;
}

The problem while debugging were: While executed at main.cpp crc(bytes, size);,the bytes's address value shown on VS Code VARIABLES was 0x55555556aeb0. While executed at crc.cpp uint16_t crc = 0;,the ptr's address value shown on VS Code VARIABLES was 0x55555556aeb2. While executed at crc.cpp for (int i = 0; i < count; ++i),the ptr shown was 0x55555556aeb4. While executed at crc.cpp crc = crc ^ (static_cast<uint16_t>(*(ptr + i)) << 8);,was 0x55555556aeb5. Anyway, once excuted a step ,once it increased 0x02.

What happened? Obviously, I expect the address pointed to by ptr in crc to be unchanged. I also tried to just run and the output was just fine. So the problem is the code work while run but not while debugging.

Did I used pointer in a wrong way? Did I had a wrong debug setup? How can I fix this?

Upvotes: 1

Views: 88

Answers (0)

Related Questions