Исключение Protobuf при выделении памяти для строки в dll

Я использую protobuf 3 для сериализации простого сообщения.

Я получаю плохое распределение, когда устанавливаю строковое значение для одного из участников моего сообщения protobuf, как это.

std::string a("eeee");
hello_in.set_name(a);

Исключение плохого распределения происходит в libprotobuf.dll в этой функции ...

 void CreateInstance(Arena* arena, const ::std::string* initial_value) {
    GOOGLE_DCHECK(initial_value != NULL);
    // uses "new ::std::string" when arena is nullptr
    ptr_ = Arena::Create< ::std::string>(arena, *initial_value);
  }

Но я думаю, что настоящая проблема в том, что initial_value каким-то образом поврежден и имеет размер [size] = 3435973836.

Не знаю, как это происходит. CreateInstance действительно вызывается несколько раз до этого, но это первый раз, когда он вызывается из main.cpp. Это заставляет меня думать, что это имеет какое-то отношение к DLL и владению меморией.

Использование любой из других функций set_name также вызывает исключение неверного распределения. Установка bool или int в сообщении работает нормально.

Вот сообщение и main.cpp. Я не включил hello.pb.h / pb.cc, поскольку они довольно большие, но могут, если это поможет.

// See README.txt for information and build instructions.
//
// Note: START and END tags are used in comments to define sections used in
// tutorials.  They are not part of the syntax for Protocol Buffers.
//
// To get an in-depth walkthrough of this file and the related examples, see:
// https://developers.google.com/protocol-buffers/docs/tutorials

// [START declaration]
syntax = "proto3";
package commands;

import "google/protobuf/timestamp.proto";
// [END declaration]

// [START messages]
message Hello {
    string name = 1;
    int32 id = 2;  // Unique ID number for this person.
    bool on = 3;
    google.protobuf.Timestamp last_updated = 4;
}

// [END messages]

#include "hello.pb.h"

//  stl
#include <fstream>
#include <iostream>

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    commands::Hello hello_in;
    hello_in.set_id(2);
    std::string a("eeee");
    hello_in.set_name(a);    
    hello_in.set_on(false);

    {
        // Write the new address book back to disk.
        std::fstream output("hello.txt", std::ios::out | std::ios::trunc | std::ios::binary);
        if (!hello_in.SerializeToOstream(&output)) {
            std::cerr << "Failed to write address book." << std::endl;
            return -1;
        }
    }

    commands::Hello hello_out;

    {
        // Read the existing address book.
        std::fstream input("hello.txt", std::ios::in | std::ios::binary);
        if (!input) {
            std::cout << "hello.txt" << ": File not found.  Creating a new file." << std::endl;
        }
        else if (!hello_out.ParseFromIstream(&input)) {
            std::cerr << "Failed to parse address book." << std::endl;
            return -1;
        }
    }

    // Optional:  Delete all global objects allocated by libprotobuf.
    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

person ariia    schedule 05.07.2020    source источник
comment
К вашему сведению: он отлично работает на Ubuntu 18.04. Вы пробовали hello_in.set_name("eeee");?   -  person Azeem    schedule 07.07.2020
comment
@ Азим, да. это не решает проблему.   -  person ariia    schedule 07.07.2020
comment
Рассмотрите возможность создания проблемы для этого в репозитории GitHub. Сначала проверьте существующие проблемы на сходство.   -  person Azeem    schedule 07.07.2020


Ответы (1)


Я наблюдал такое же поведение (проект Visual Studio 2019 C ++). Решение, которое мне помогло: libprotobuf.lib и libprotobuf.dll были заменены в режиме debug / x86 его отладочной версией libprotobufd.lib и libprotobufd.dll.

person Norbert Kees    schedule 05.10.2020