You need to enable JavaScript to run this app. 无bitset/vector的LSB图像隐写编解码实现异常排查
优惠活动
大模型
产品
解决方案
定价
更多

无bitset/vector的LSB图像隐写编解码实现异常排查

LSB图像隐写程序问题排查与修复

现存核心问题

编码器逻辑问题

  • 未初始化变量c直接用于动态内存分配,new int[c]/new int*[c]会因c为随机值触发内存越界;且分配的messageASCII、messageBinary全程未被使用,存在内存泄漏
  • 二进制输出循环结束后,索引top值为-1,后续嵌入逻辑直接从top=-1开始访问数组元素,触发内存越界
  • 嵌入流程无终止条件:本应仅嵌入8位单字符,却遍历了整张图片的所有像素通道,写入大量无效数据
  • 比特索引混乱:未按m数组的存储顺序依次写入LSB,导致嵌入的比特顺序完全错位

解码器逻辑问题

  • 未初始化变量i直接作为数组长度定义char array[i],属于非法栈内存分配,会触发栈溢出
  • 位计数逻辑错误:bitcount达到8才清零的判断顺序错误,导致数组访问越界,且计数节奏与编码器写入顺序不匹配
  • 字符转换逻辑位置错误:每读取1个像素位就立即执行8位转ASCII的计算,完全未等凑齐8个有效位再转换
  • 累加变量total未初始化,每次计算都会叠加栈上的脏值,结果完全不可控
  • 解码流程无终止条件:会遍历整张图的所有像素位,把剩余像素的LSB全部转换为无意义的垃圾字符
  • 位权计算使用pow(2,i)浮点数运算,存在浮点精度误差,会导致转换结果错误

修复后代码

编码器

#include "BitmapHelper.h"
#include <iostream>
using namespace std;

void encodeMessage(unsigned char*** imageData, int imageWidth, int imageHeight) {
    cout << "Please enter the message you want embedded in this image (Letter)" << endl;
    char message;
    cin >> message;

    // 转换为8位二进制数组,m[0]存储最低位,m[7]存储最高位
    int m[8];
    char temp = message;
    for (int k = 0; k < 8; k++) {
        m[k] = temp % 2;
        temp = temp / 2;
    }

    // 依次写入像素LSB,凑够8位立即停止遍历
    int bitIdx = 0;
    for (int row = 0; row < imageHeight && bitIdx < 8; row++) {
        for (int col = 0; col < imageWidth && bitIdx < 8; col++) {
            for (int channel = 0; channel < 3 && bitIdx < 8; channel++) {
                // 清除原像素的LSB位,写入对应嵌入位
                imageData[row][col][channel] = (imageData[row][col][channel] & ~1) | m[bitIdx];
                bitIdx++;
            }
        }
    }
}

解码器

#include <string>
#include <iostream>
using namespace std;

void decodeMessage(int imageHeight, int imageWidth, unsigned char*** imageData) {
    int bitcount = 0;
    int bits[8] = {0}; // 固定长度数组存储8位待转换比特
    char decodedChar = 0;
    string message;

    for (int row = 0; row < imageHeight; row++) {
        for (int col = 0; col < imageWidth; col++) {
            for (int channel = 0; channel < 3; channel++) {
                // 提取当前像素通道的LSB位
                int bit = imageData[row][col][channel] % 2;
                bits[bitcount] = bit;
                bitcount++;

                // 凑够8位立即转换为ASCII字符
                if (bitcount == 8) {
                    bitcount = 0;
                    decodedChar = 0;
                    // 用位运算计算位权,避免浮点精度误差
                    for (int i = 0; i < 8; i++) {
                        decodedChar += bits[i] << i;
                    }
                    message += decodedChar;
                    // 单字符场景下转换完成立即退出,避免读取无效垃圾数据
                    goto exit_decode;
                }
            }
        }
    }
exit_decode:
    cout << "Decoded message: " << message << endl;
}

内容的提问来源于stack exchange,提问作者mariam aldhaheri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 11:24:08