c++ - 在 Linux/Unix 问题 C++ 中编译

标签 c++ linux unix

这只是整个程序的一部分,在 Windows 中编译和运行良好,但它不喜欢我在 Linux/Unix 中的 strcpy。我做错了什么,我该如何解决?另外请注意,我不允许使用字符串,只能使用 cstring。

歌曲.cpp

#include "Song.h"


Song::Song()
{
}


Song::~Song()
{
}


Song::Song(char* title, char* artist, char* duration, char* album)
{
strcpy(this->title,50,title);
strcpy(this->artist, 50, artist);
strcpy(this->duration, 50, duration);
strcpy(this->album, 50, album);
}

void Song::setTitle(char* title)
{
this->title= title;
}
void Song::setArtist(char* artist)
{
this->artist = artist;
}
void Song::setDuration(char* duration)
{
this->duration= duration;
}
void Song::setAlbum(char* album)
{
this->album= album;
}

char* Song::getTitle()
{
return this->title;
}
char* Song::getArtist()
{
return this->artist;
}
char* Song::getDuration()
{
return this->duration;
}
char* Song::getAlbum()
{
return this->album;
}

宋.h

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cctype>

using namespace std;

class Song
{
private:
    char* title;
    char* artist;
    char* duration;
    char* album;

public:
    Song();
    ~Song();

    Song(char* title, char* artist, char* duration, char* album);

    void setTitle(char* title);
    void setArtist(char* artist);
    void setDuration(char* duration);
    void setAlbum(char* album);

    char* getTitle();
    char* getArtist();
    char* getDuration();
    char* getAlbum();


};

最佳答案

您还没有为 strcpy 分配任何内存以复制到其中。因此,您的构造函数会调用未定义的行为。

你需要先分配一个字符数组。但是你还需要在你的每个 setter 中取消分配它。否则内存将泄漏,因为您正在重新分配管理它的指针。

关于c++ - 在 Linux/Unix 问题 C++ 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489891/

相关文章:

c++ - 只有当 len < 3 时,我才会收到堆损坏错误。怎么会?

c++ - "New"运算符的不同行为 - 动态内存分配

c++ - 使用指针创建类成员

linux - Ping on bash 脚本,ping 如果失败则退出脚本

linux - 在 shell 函数中赋值给命名变量

python - 将 shell 命令的输出通过管道传输到 python 脚本

c++ - 为什么 while 体被执行?

linux - find 命令查找文件并连接它们

linux - 从套接字写入输出

linux - 使用命令在 linux 终端中运行 c++ 程序