簡體   English   中英

在結構之間復制char數據

[英]Copying char data between structs

我的代碼中出現數據中止異常。 我很可能對char進行了非常糟糕的操作。 該代碼似乎有效,但是我想知道它是否實際上是無效的。 問題是,如果將涉及一個字符數組的一個結構的數據復制到另一個結構,會發生什么情況。 數據如何復制?

我有兩個功能,一是將故意泄露的,因為我也想知道,如果用結構創建會發生什么new的目的地的生命,但其數據復制它的結構超出范圍。

// Example program
#include <iostream>
#include <string>
#include "string.h"

typedef struct {
    char name[12];
    char stupid[12];
    int hello;
} tFile;

void CopyFileAndDelete(tFile *file1){
    tFile *file2 = new tFile;
    *file2 = *file1;
    std::cout << file2->name << std::endl;
    delete file2;
}

void CopyFileAndLeak(tFile *file1){
    tFile *file2 = new tFile;
    *file2 = *file1;
    std::cout << file2->name << std::endl;
}

int main()
{
    tFile file1;
    memset(&file1, 0, sizeof file1);
    file1.hello = 22;
    snprintf(file1.name, 12, "%s", "hellogoodfriendhwoareyou");
    snprintf(file1.stupid, 12, "%s", "greate");
    CopyFileAndDelete(&file1);

    CopyFileAndLeak(&file1);
}

除了此代碼通常不安全並且C語言比C ++語言更多外,它是正確的(除了泄漏)。這不可能產生異常(除非由於內存分配失敗而導致new拋出)。

結構內部的數組將按照您的期望進行復制。 編譯器通常會執行memcpy()復制它們(或使用類似memcpy的特殊內置memcpy來優化復制操作。)

這不是您應該編寫的代碼。 使用std::string代替。 不要使用newdelete ,而是使用值類型。 如果確實需要分配,請使用unique_ptrshared_ptr進行分配。

不要在C ++中寫這樣的代碼:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM