(svn r26509) -Codechange: replace strdup with stredup (the latter ensures the return is not NULL)

pull/155/head
rubidium 10 years ago
parent 0b159549d4
commit 034735a54c

@ -11,6 +11,7 @@
#include "../stdafx.h" #include "../stdafx.h"
#include "../settings_type.h" #include "../settings_type.h"
#include "../string_func.h"
#include "ai.hpp" #include "ai.hpp"
#include "ai_config.hpp" #include "ai_config.hpp"
#include "ai_info.hpp" #include "ai_info.hpp"
@ -109,7 +110,7 @@ void AIConfig::SetSetting(const char *name, int value)
if (it != this->settings.end()) { if (it != this->settings.end()) {
(*it).second = value; (*it).second = value;
} else { } else {
this->settings[strdup(name)] = value; this->settings[stredup(name)] = value;
} }
return; return;

@ -15,6 +15,7 @@
#include "ai_info.hpp" #include "ai_info.hpp"
#include "ai_scanner.hpp" #include "ai_scanner.hpp"
#include "../debug.h" #include "../debug.h"
#include "../string_func.h"
#include "../rev.h" #include "../rev.h"
#include "../safeguards.h" #include "../safeguards.h"
@ -71,8 +72,8 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
if (res != 0) return res; if (res != 0) return res;
ScriptConfigItem config = _start_date_config; ScriptConfigItem config = _start_date_config;
config.name = strdup(config.name); config.name = stredup(config.name);
config.description = strdup(config.description); config.description = stredup(config.description);
info->config_list.push_front(config); info->config_list.push_front(config);
if (info->engine->MethodExists(*info->SQ_instance, "MinVersionToLoad")) { if (info->engine->MethodExists(*info->SQ_instance, "MinVersionToLoad")) {
@ -94,7 +95,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
return SQ_ERROR; return SQ_ERROR;
} }
} else { } else {
info->api_version = strdup("0.7"); info->api_version = stredup("0.7");
} }
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */ /* Remove the link to the real instance, else it might get deleted by RegisterAI() */
@ -117,7 +118,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
char buf[8]; char buf[8];
seprintf(buf, lastof(buf), "%d.%d", GB(_openttd_newgrf_version, 28, 4), GB(_openttd_newgrf_version, 24, 4)); seprintf(buf, lastof(buf), "%d.%d", GB(_openttd_newgrf_version, 28, 4), GB(_openttd_newgrf_version, 24, 4));
info->api_version = strdup(buf); info->api_version = stredup(buf);
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */ /* Remove the link to the real instance, else it might get deleted by RegisterAI() */
sq_setinstanceup(vm, 2, NULL); sq_setinstanceup(vm, 2, NULL);

@ -33,7 +33,7 @@ void AIScannerInfo::Initialize()
/* Create the dummy AI */ /* Create the dummy AI */
free(this->main_script); free(this->main_script);
this->main_script = strdup("%_dummy"); this->main_script = stredup("%_dummy");
extern void Script_CreateDummyInfo(HSQUIRRELVM vm, const char *type, const char *dir); extern void Script_CreateDummyInfo(HSQUIRRELVM vm, const char *type, const char *dir);
Script_CreateDummyInfo(this->engine->GetVM(), "AI", "ai"); Script_CreateDummyInfo(this->engine->GetVM(), "AI", "ai");
} }

@ -12,6 +12,7 @@
#include "stdafx.h" #include "stdafx.h"
#include "base_consist.h" #include "base_consist.h"
#include "vehicle_base.h" #include "vehicle_base.h"
#include "string_func.h"
#include "safeguards.h" #include "safeguards.h"
@ -29,7 +30,7 @@ void BaseConsist::CopyConsistPropertiesFrom(const BaseConsist *src)
if (this == src) return; if (this == src) return;
free(this->name); free(this->name);
this->name = src->name != NULL ? strdup(src->name) : NULL; this->name = src->name != NULL ? stredup(src->name) : NULL;
this->current_order_time = src->current_order_time; this->current_order_time = src->current_order_time;
this->lateness_counter = src->lateness_counter; this->lateness_counter = src->lateness_counter;

@ -51,16 +51,16 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
IniItem *item; IniItem *item;
fetch_metadata("name"); fetch_metadata("name");
this->name = strdup(item->value); this->name = stredup(item->value);
fetch_metadata("description"); fetch_metadata("description");
this->description[strdup("")] = strdup(item->value); this->description[stredup("")] = stredup(item->value);
/* Add the translations of the descriptions too. */ /* Add the translations of the descriptions too. */
for (const IniItem *item = metadata->item; item != NULL; item = item->next) { for (const IniItem *item = metadata->item; item != NULL; item = item->next) {
if (strncmp("description.", item->name, 12) != 0) continue; if (strncmp("description.", item->name, 12) != 0) continue;
this->description[strdup(item->name + 12)] = strdup(item->value); this->description[stredup(item->name + 12)] = stredup(item->value);
} }
fetch_metadata("shortname"); fetch_metadata("shortname");
@ -129,9 +129,9 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
if (item == NULL) item = origin->GetItem("default", false); if (item == NULL) item = origin->GetItem("default", false);
if (item == NULL) { if (item == NULL) {
DEBUG(grf, 1, "No origin warning message specified for: %s", filename); DEBUG(grf, 1, "No origin warning message specified for: %s", filename);
file->missing_warning = strdup(""); file->missing_warning = stredup("");
} else { } else {
file->missing_warning = strdup(item->value); file->missing_warning = stredup(item->value);
} }
switch (T::CheckMD5(file, BASESET_DIR)) { switch (T::CheckMD5(file, BASESET_DIR)) {
@ -164,7 +164,7 @@ bool BaseMedia<Tbase_set>::AddFile(const char *filename, size_t basepath_length,
IniFile *ini = new IniFile(); IniFile *ini = new IniFile();
ini->LoadFromDisk(filename, BASESET_DIR); ini->LoadFromDisk(filename, BASESET_DIR);
char *path = strdup(filename + basepath_length); char *path = stredup(filename + basepath_length);
char *psep = strrchr(path, PATHSEPCHAR); char *psep = strrchr(path, PATHSEPCHAR);
if (psep != NULL) { if (psep != NULL) {
psep[1] = '\0'; psep[1] = '\0';

@ -63,7 +63,7 @@ protected:
* @pre There is no blitter registered with this name. * @pre There is no blitter registered with this name.
*/ */
BlitterFactory(const char *name, const char *description, bool usable = true) : BlitterFactory(const char *name, const char *description, bool usable = true) :
name(strdup(name)), description(strdup(description)) name(stredup(name)), description(stredup(description))
{ {
if (usable) { if (usable) {
/* /*

@ -1114,7 +1114,7 @@ CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
Company *c = Company::Get(_current_company); Company *c = Company::Get(_current_company);
free(c->name); free(c->name);
c->name = reset ? NULL : strdup(text); c->name = reset ? NULL : stredup(text);
MarkWholeScreenDirty(); MarkWholeScreenDirty();
CompanyAdminUpdate(c); CompanyAdminUpdate(c);
} }
@ -1163,7 +1163,7 @@ CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (reset) { if (reset) {
c->president_name = NULL; c->president_name = NULL;
} else { } else {
c->president_name = strdup(text); c->president_name = stredup(text);
if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) { if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
char buf[80]; char buf[80];

@ -105,7 +105,7 @@ void IConsolePrint(TextColour colour_code, const char *string)
/* Create a copy of the string, strip if of colours and invalid /* Create a copy of the string, strip if of colours and invalid
* characters and (when applicable) assign it to the console buffer */ * characters and (when applicable) assign it to the console buffer */
str = strdup(string); str = stredup(string);
str_strip_colours(str); str_strip_colours(str);
str_validate(str, str + strlen(str)); str_validate(str, str + strlen(str));
@ -256,7 +256,7 @@ char *RemoveUnderscores(char *name)
void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook) void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook)
{ {
IConsoleCmd *item_new = MallocT<IConsoleCmd>(1); IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
item_new->name = RemoveUnderscores(strdup(name)); item_new->name = RemoveUnderscores(stredup(name));
item_new->next = NULL; item_new->next = NULL;
item_new->proc = proc; item_new->proc = proc;
item_new->hook = hook; item_new->hook = hook;
@ -291,8 +291,8 @@ void IConsoleAliasRegister(const char *name, const char *cmd)
return; return;
} }
char *new_alias = RemoveUnderscores(strdup(name)); char *new_alias = RemoveUnderscores(stredup(name));
char *cmd_aliased = strdup(cmd); char *cmd_aliased = stredup(cmd);
IConsoleAlias *item_new = MallocT<IConsoleAlias>(1); IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
item_new->next = NULL; item_new->next = NULL;

@ -1344,7 +1344,7 @@ DEF_CONSOLE_CMD(ConAlias)
IConsoleAliasRegister(argv[1], argv[2]); IConsoleAliasRegister(argv[1], argv[2]);
} else { } else {
free(alias->cmdline); free(alias->cmdline);
alias->cmdline = strdup(argv[2]); alias->cmdline = stredup(argv[2]);
} }
return true; return true;
} }

@ -465,7 +465,7 @@ static const char *IConsoleHistoryAdd(const char *cmd)
if (_iconsole_history[0] == NULL || strcmp(_iconsole_history[0], cmd) != 0) { if (_iconsole_history[0] == NULL || strcmp(_iconsole_history[0], cmd) != 0) {
free(_iconsole_history[ICON_HISTORY_SIZE - 1]); free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1)); memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
_iconsole_history[0] = strdup(cmd); _iconsole_history[0] = stredup(cmd);
} }
/* Reset the history position */ /* Reset the history position */

@ -70,7 +70,7 @@ CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
d->name = NULL; d->name = NULL;
MakeDefaultName(d); MakeDefaultName(d);
} else { } else {
d->name = strdup(text); d->name = stredup(text);
} }
/* Update the orders and depot */ /* Update the orders and depot */

@ -208,7 +208,7 @@ DriverFactoryBase::DriverFactoryBase(Driver::Type type, int priority, const char
strecpy(buf, GetDriverTypeName(type), lastof(buf)); strecpy(buf, GetDriverTypeName(type), lastof(buf));
strecpy(buf + 5, name, lastof(buf)); strecpy(buf + 5, name, lastof(buf));
const char *longname = strdup(buf); const char *longname = stredup(buf);
std::pair<Drivers::iterator, bool> P = GetDrivers().insert(Drivers::value_type(longname, this)); std::pair<Drivers::iterator, bool> P = GetDrivers().insert(Drivers::value_type(longname, this));
assert(P.second); assert(P.second);

@ -1027,7 +1027,7 @@ CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
if (reset) { if (reset) {
e->name = NULL; e->name = NULL;
} else { } else {
e->name = strdup(text); e->name = stredup(text);
} }
MarkWholeScreenDirty(); MarkWholeScreenDirty();

@ -77,7 +77,7 @@ ErrorMessageData::ErrorMessageData(const ErrorMessageData &data)
*this = data; *this = data;
for (size_t i = 0; i < lengthof(this->strings); i++) { for (size_t i = 0; i < lengthof(this->strings); i++) {
if (this->strings[i] != NULL) { if (this->strings[i] != NULL) {
this->strings[i] = strdup(this->strings[i]); this->strings[i] = stredup(this->strings[i]);
this->decode_params[i] = (size_t)this->strings[i]; this->decode_params[i] = (size_t)this->strings[i];
} }
} }
@ -158,7 +158,7 @@ void ErrorMessageData::SetDParam(uint n, uint64 v)
void ErrorMessageData::SetDParamStr(uint n, const char *str) void ErrorMessageData::SetDParamStr(uint n, const char *str)
{ {
free(this->strings[n]); free(this->strings[n]);
this->strings[n] = strdup(str); this->strings[n] = stredup(str);
} }
/** Define a queue with errors. */ /** Define a queue with errors. */

@ -265,7 +265,7 @@ void FioOpenFile(int slot, const char *filename, Subdirectory subdir)
/* Store the filename without path and extension */ /* Store the filename without path and extension */
const char *t = strrchr(filename, PATHSEPCHAR); const char *t = strrchr(filename, PATHSEPCHAR);
_fio.shortnames[slot] = strdup(t == NULL ? filename : t); _fio.shortnames[slot] = stredup(t == NULL ? filename : t);
char *t2 = strrchr(_fio.shortnames[slot], '.'); char *t2 = strrchr(_fio.shortnames[slot], '.');
if (t2 != NULL) *t2 = '\0'; if (t2 != NULL) *t2 = '\0';
strtolower(_fio.shortnames[slot]); strtolower(_fio.shortnames[slot]);
@ -755,7 +755,7 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
* been given read access. */ * been given read access. */
if (f == NULL) return false; if (f == NULL) return false;
const char *dupped_filename = strdup(filename); const char *dupped_filename = stredup(filename);
_tar_list[this->subdir][filename].filename = dupped_filename; _tar_list[this->subdir][filename].filename = dupped_filename;
_tar_list[this->subdir][filename].dirname = NULL; _tar_list[this->subdir][filename].dirname = NULL;
@ -892,7 +892,7 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
/* Store the first directory name we detect */ /* Store the first directory name we detect */
DEBUG(misc, 6, "Found dir in tar: %s", name); DEBUG(misc, 6, "Found dir in tar: %s", name);
if (_tar_list[this->subdir][filename].dirname == NULL) _tar_list[this->subdir][filename].dirname = strdup(name); if (_tar_list[this->subdir][filename].dirname == NULL) _tar_list[this->subdir][filename].dirname = stredup(name);
break; break;
default: default:
@ -1091,7 +1091,7 @@ void DetermineBasePaths(const char *exe)
free(xdg_data_home); free(xdg_data_home);
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_PERSONAL_DIR_XDG] = strdup(tmp); _searchpaths[SP_PERSONAL_DIR_XDG] = stredup(tmp);
#endif #endif
#if defined(__MORPHOS__) || defined(__AMIGA__) || defined(DOS) || defined(OS2) || !defined(WITH_PERSONAL_DIR) #if defined(__MORPHOS__) || defined(__AMIGA__) || defined(DOS) || defined(OS2) || !defined(WITH_PERSONAL_DIR)
_searchpaths[SP_PERSONAL_DIR] = NULL; _searchpaths[SP_PERSONAL_DIR] = NULL;
@ -1099,7 +1099,7 @@ void DetermineBasePaths(const char *exe)
#ifdef __HAIKU__ #ifdef __HAIKU__
BPath path; BPath path;
find_directory(B_USER_SETTINGS_DIRECTORY, &path); find_directory(B_USER_SETTINGS_DIRECTORY, &path);
const char *homedir = strdup(path.Path()); const char *homedir = stredup(path.Path());
#else #else
/* getenv is highly unsafe; duplicate it as soon as possible, /* getenv is highly unsafe; duplicate it as soon as possible,
* or at least before something else touches the environment * or at least before something else touches the environment
@ -1112,7 +1112,7 @@ void DetermineBasePaths(const char *exe)
if (homedir == NULL) { if (homedir == NULL) {
const struct passwd *pw = getpwuid(getuid()); const struct passwd *pw = getpwuid(getuid());
homedir = (pw == NULL) ? NULL : strdup(pw->pw_dir); homedir = (pw == NULL) ? NULL : stredup(pw->pw_dir);
} }
#endif #endif
@ -1121,7 +1121,7 @@ void DetermineBasePaths(const char *exe)
seprintf(tmp, lastof(tmp), "%s" PATHSEP "%s", homedir, PERSONAL_DIR); seprintf(tmp, lastof(tmp), "%s" PATHSEP "%s", homedir, PERSONAL_DIR);
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_PERSONAL_DIR] = strdup(tmp); _searchpaths[SP_PERSONAL_DIR] = stredup(tmp);
free(homedir); free(homedir);
} else { } else {
_searchpaths[SP_PERSONAL_DIR] = NULL; _searchpaths[SP_PERSONAL_DIR] = NULL;
@ -1131,7 +1131,7 @@ void DetermineBasePaths(const char *exe)
#if defined(WITH_SHARED_DIR) #if defined(WITH_SHARED_DIR)
seprintf(tmp, lastof(tmp), "%s", SHARED_DIR); seprintf(tmp, lastof(tmp), "%s", SHARED_DIR);
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_SHARED_DIR] = strdup(tmp); _searchpaths[SP_SHARED_DIR] = stredup(tmp);
#else #else
_searchpaths[SP_SHARED_DIR] = NULL; _searchpaths[SP_SHARED_DIR] = NULL;
#endif #endif
@ -1141,7 +1141,7 @@ void DetermineBasePaths(const char *exe)
#else #else
if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0'; if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_WORKING_DIR] = strdup(tmp); _searchpaths[SP_WORKING_DIR] = stredup(tmp);
#endif #endif
_do_scan_working_directory = DoScanWorkingDirectory(); _do_scan_working_directory = DoScanWorkingDirectory();
@ -1150,7 +1150,7 @@ void DetermineBasePaths(const char *exe)
if (ChangeWorkingDirectoryToExecutable(exe)) { if (ChangeWorkingDirectoryToExecutable(exe)) {
if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0'; if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_BINARY_DIR] = strdup(tmp); _searchpaths[SP_BINARY_DIR] = stredup(tmp);
} else { } else {
_searchpaths[SP_BINARY_DIR] = NULL; _searchpaths[SP_BINARY_DIR] = NULL;
} }
@ -1167,7 +1167,7 @@ void DetermineBasePaths(const char *exe)
#else #else
seprintf(tmp, lastof(tmp), "%s", GLOBAL_DATA_DIR); seprintf(tmp, lastof(tmp), "%s", GLOBAL_DATA_DIR);
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_INSTALLATION_DIR] = strdup(tmp); _searchpaths[SP_INSTALLATION_DIR] = stredup(tmp);
#endif #endif
#ifdef WITH_COCOA #ifdef WITH_COCOA
extern void cocoaSetApplicationBundleDir(); extern void cocoaSetApplicationBundleDir();
@ -1209,7 +1209,7 @@ void DeterminePaths(const char *exe)
char *config_dir; char *config_dir;
if (_config_file != NULL) { if (_config_file != NULL) {
config_dir = strdup(_config_file); config_dir = stredup(_config_file);
char *end = strrchr(config_dir, PATHSEPCHAR); char *end = strrchr(config_dir, PATHSEPCHAR);
if (end == NULL) { if (end == NULL) {
config_dir[0] = '\0'; config_dir[0] = '\0';
@ -1221,7 +1221,7 @@ void DeterminePaths(const char *exe)
if (FioFindFullPath(personal_dir, lastof(personal_dir), BASE_DIR, "openttd.cfg") != NULL) { if (FioFindFullPath(personal_dir, lastof(personal_dir), BASE_DIR, "openttd.cfg") != NULL) {
char *end = strrchr(personal_dir, PATHSEPCHAR); char *end = strrchr(personal_dir, PATHSEPCHAR);
if (end != NULL) end[1] = '\0'; if (end != NULL) end[1] = '\0';
config_dir = strdup(personal_dir); config_dir = stredup(personal_dir);
_config_file = str_fmt("%sopenttd.cfg", config_dir); _config_file = str_fmt("%sopenttd.cfg", config_dir);
} else { } else {
#if defined(WITH_XDG_BASEDIR) && defined(WITH_PERSONAL_DIR) #if defined(WITH_XDG_BASEDIR) && defined(WITH_PERSONAL_DIR)
@ -1235,7 +1235,7 @@ void DeterminePaths(const char *exe)
config_dir = NULL; config_dir = NULL;
for (uint i = 0; i < lengthof(new_openttd_cfg_order); i++) { for (uint i = 0; i < lengthof(new_openttd_cfg_order); i++) {
if (IsValidSearchPath(new_openttd_cfg_order[i])) { if (IsValidSearchPath(new_openttd_cfg_order[i])) {
config_dir = strdup(_searchpaths[new_openttd_cfg_order[i]]); config_dir = stredup(_searchpaths[new_openttd_cfg_order[i]]);
break; break;
} }
} }

@ -566,7 +566,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
char *font_family; char *font_family;
/* Split & strip the font's style */ /* Split & strip the font's style */
font_family = strdup(font_name); font_family = stredup(font_name);
font_style = strchr(font_family, ','); font_style = strchr(font_family, ',');
if (font_style != NULL) { if (font_style != NULL) {
font_style[0] = '\0'; font_style[0] = '\0';

@ -212,7 +212,7 @@ struct StringNameWriter : HeaderWriter {
void WriteStringID(const char *name, int stringid) void WriteStringID(const char *name, int stringid)
{ {
if (stringid == (int)this->strings->Length()) *this->strings->Append() = strdup(name); if (stringid == (int)this->strings->Length()) *this->strings->Append() = stredup(name);
} }
void Finalise(const StringData &data) void Finalise(const StringData &data)
@ -231,7 +231,7 @@ private:
public: public:
/** Initialise */ /** Initialise */
LanguageScanner(GameStrings *gs, const char *exclude) : gs(gs), exclude(strdup(exclude)) {} LanguageScanner(GameStrings *gs, const char *exclude) : gs(gs), exclude(stredup(exclude)) {}
~LanguageScanner() { free(exclude); } ~LanguageScanner() { free(exclude); }
/** /**

@ -462,7 +462,7 @@ void GamelogSetting(const char *name, int32 oldval, int32 newval)
LoggedChange *lc = GamelogChange(GLCT_SETTING); LoggedChange *lc = GamelogChange(GLCT_SETTING);
if (lc == NULL) return; if (lc == NULL) return;
lc->setting.name = strdup(name); lc->setting.name = stredup(name);
lc->setting.oldval = oldval; lc->setting.oldval = oldval;
lc->setting.newval = newval; lc->setting.newval = newval;
} }

@ -90,7 +90,7 @@ CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
g->type = type; g->type = type;
g->dst = p2; g->dst = p2;
g->company = company; g->company = company;
g->text = strdup(text); g->text = stredup(text);
g->progress = NULL; g->progress = NULL;
g->completed = false; g->completed = false;
@ -155,7 +155,7 @@ CommandCost CmdSetGoalText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
Goal *g = Goal::Get(p1); Goal *g = Goal::Get(p1);
free(g->text); free(g->text);
g->text = strdup(text); g->text = stredup(text);
if (g->company == INVALID_COMPANY) { if (g->company == INVALID_COMPANY) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
@ -187,7 +187,7 @@ CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (StrEmpty(text)) { if (StrEmpty(text)) {
g->progress = NULL; g->progress = NULL;
} else { } else {
g->progress = strdup(text); g->progress = stredup(text);
} }
if (g->company == INVALID_COMPANY) { if (g->company == INVALID_COMPANY) {

@ -23,6 +23,7 @@
#include "company_base.h" #include "company_base.h"
#include "story_base.h" #include "story_base.h"
#include "command_func.h" #include "command_func.h"
#include "string_func.h"
#include "widgets/goal_widget.h" #include "widgets/goal_widget.h"
@ -364,7 +365,7 @@ struct GoalQuestionWindow : public Window {
GoalQuestionWindow(WindowDesc *desc, WindowNumber window_number, byte type, uint32 button_mask, const char *question) : Window(desc), type(type) GoalQuestionWindow(WindowDesc *desc, WindowNumber window_number, byte type, uint32 button_mask, const char *question) : Window(desc), type(type)
{ {
assert(type < GOAL_QUESTION_TYPE_COUNT); assert(type < GOAL_QUESTION_TYPE_COUNT);
this->question = strdup(question); this->question = stredup(question);
/* Figure out which buttons we have to enable. */ /* Figure out which buttons we have to enable. */
uint bit; uint bit;

@ -392,7 +392,7 @@ CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Delete the old name */ /* Delete the old name */
free(g->name); free(g->name);
/* Assign the new one */ /* Assign the new one */
g->name = reset ? NULL : strdup(text); g->name = reset ? NULL : stredup(text);
} }
} else { } else {
/* Set group parent */ /* Set group parent */

@ -141,7 +141,7 @@ static void ParseHotkeys(Hotkey *hotkey, const char *value)
* by a '+'. * by a '+'.
* @param keycode The keycode to convert to a string. * @param keycode The keycode to convert to a string.
* @return A string representation of this keycode. * @return A string representation of this keycode.
* @note The return value is a static buffer, strdup the result before calling * @note The return value is a static buffer, stredup the result before calling
* this function again. * this function again.
*/ */
static const char *KeycodeToString(uint16 keycode) static const char *KeycodeToString(uint16 keycode)
@ -195,7 +195,7 @@ static const char *KeycodeToString(uint16 keycode)
* keycodes are attached to the hotkey they are split by a comma. * keycodes are attached to the hotkey they are split by a comma.
* @param hotkey The keycodes of this hotkey need to be converted to a string. * @param hotkey The keycodes of this hotkey need to be converted to a string.
* @return A string representation of all keycodes. * @return A string representation of all keycodes.
* @note The return value is a static buffer, strdup the result before calling * @note The return value is a static buffer, stredup the result before calling
* this function again. * this function again.
*/ */
const char *SaveKeycodes(const Hotkey *hotkey) const char *SaveKeycodes(const Hotkey *hotkey)

@ -49,7 +49,7 @@ IniItem::~IniItem()
void IniItem::SetValue(const char *value) void IniItem::SetValue(const char *value)
{ {
free(this->value); free(this->value);
this->value = strdup(value); this->value = stredup(value);
} }
/** /**
@ -168,7 +168,7 @@ IniGroup *IniLoadFile::GetGroup(const char *name, size_t len, bool create_new)
/* otherwise make a new one */ /* otherwise make a new one */
IniGroup *group = new IniGroup(this, name, name + len - 1); IniGroup *group = new IniGroup(this, name, name + len - 1);
group->comment = strdup("\n"); group->comment = stredup("\n");
return group; return group;
} }

@ -946,7 +946,7 @@ struct QueryStringWindow : public Window
this->editbox.text.UpdateSize(); this->editbox.text.UpdateSize();
if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig = strdup(this->editbox.text.buf); if ((flags & QSF_ACCEPT_UNCHANGED) == 0) this->editbox.orig = stredup(this->editbox.text.buf);
this->querystrings[WID_QS_TEXT] = &this->editbox; this->querystrings[WID_QS_TEXT] = &this->editbox;
this->editbox.caption = caption; this->editbox.caption = caption;

@ -45,7 +45,7 @@ const char *MusicDriver_ExtMidi::Start(const char * const * parm)
const char *command = GetDriverParam(parm, "cmd"); const char *command = GetDriverParam(parm, "cmd");
if (StrEmpty(command)) command = EXTERNAL_PLAYER; if (StrEmpty(command)) command = EXTERNAL_PLAYER;
this->command = strdup(command); this->command = stredup(command);
this->song[0] = '\0'; this->song[0] = '\0';
this->pid = -1; this->pid = -1;
return NULL; return NULL;

@ -96,7 +96,7 @@ public:
const char *data = NULL, int depth = 0) : const char *data = NULL, int depth = 0) :
TCPConnecter(address), TCPConnecter(address),
callback(callback), callback(callback),
url(strdup(url)), url(stredup(url)),
data(data), data(data),
depth(depth) depth(depth)
{ {

@ -653,7 +653,7 @@ void NetworkRebuildHostList()
_network_host_list.Clear(); _network_host_list.Clear();
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) { for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
if (item->manually) *_network_host_list.Append() = strdup(item->address.GetAddressAsString(false)); if (item->manually) *_network_host_list.Append() = stredup(item->address.GetAddressAsString(false));
} }
} }

@ -391,7 +391,7 @@ struct NetworkChatWindow : public Window {
item = 0; item = 0;
/* Copy the buffer so we can modify it without damaging the real data */ /* Copy the buffer so we can modify it without damaging the real data */
pre_buf = (_chat_tab_completion_active) ? strdup(_chat_tab_completion_buf) : strdup(tb->buf); pre_buf = (_chat_tab_completion_active) ? stredup(_chat_tab_completion_buf) : stredup(tb->buf);
tb_buf = ChatTabCompletionFindText(pre_buf); tb_buf = ChatTabCompletionFindText(pre_buf);
tb_len = strlen(tb_buf); tb_len = strlen(tb_buf);

@ -2102,7 +2102,7 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
break; break;
} }
} }
if (!contains) *_network_ban_list.Append() = strdup(ip); if (!contains) *_network_ban_list.Append() = stredup(ip);
} }
uint n = 0; uint n = 0;

@ -6006,7 +6006,7 @@ static void CfgApply(ByteReader *buf)
static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c) static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
{ {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
error->data = strdup(_cur.grfconfig->GetName()); error->data = stredup(_cur.grfconfig->GetName());
} }
/* Action 0x07 /* Action 0x07
@ -6369,7 +6369,7 @@ static void GRFLoadError(ByteReader *buf)
error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, NULL, SCC_RAW_STRING_POINTER); error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, NULL, SCC_RAW_STRING_POINTER);
} else { } else {
grfmsg(7, "GRFLoadError: No custom message supplied."); grfmsg(7, "GRFLoadError: No custom message supplied.");
error->custom_message = strdup(""); error->custom_message = stredup("");
} }
} else { } else {
error->message = msgstr[message_id]; error->message = msgstr[message_id];
@ -6381,7 +6381,7 @@ static void GRFLoadError(ByteReader *buf)
error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data); error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
} else { } else {
grfmsg(7, "GRFLoadError: No message data supplied."); grfmsg(7, "GRFLoadError: No message data supplied.");
error->data = strdup(""); error->data = stredup("");
} }
/* Only two parameter numbers can be used in the string. */ /* Only two parameter numbers can be used in the string. */
@ -6890,7 +6890,7 @@ static void GRFInhibit(ByteReader *buf)
if (file != NULL && file != _cur.grfconfig) { if (file != NULL && file != _cur.grfconfig) {
grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename); grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
error->data = strdup(_cur.grfconfig->GetName()); error->data = stredup(_cur.grfconfig->GetName());
} }
} }
} }
@ -7241,7 +7241,7 @@ static void TranslateGRFStrings(ByteReader *buf)
char tmp[256]; char tmp[256];
GetString(tmp, STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE, lastof(tmp)); GetString(tmp, STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE, lastof(tmp));
error->data = strdup(tmp); error->data = stredup(tmp);
return; return;
} }
@ -8182,7 +8182,7 @@ static void InitNewGRFFile(const GRFConfig *config)
*/ */
GRFFile::GRFFile(const GRFConfig *config) GRFFile::GRFFile(const GRFConfig *config)
{ {
this->filename = strdup(config->filename); this->filename = stredup(config->filename);
this->grfid = config->ident.grfid; this->grfid = config->ident.grfid;
/* Initialise local settings to defaults */ /* Initialise local settings to defaults */

@ -50,7 +50,7 @@ GRFConfig::GRFConfig(const char *filename) :
url(new GRFTextWrapper()), url(new GRFTextWrapper()),
num_valid_params(lengthof(param)) num_valid_params(lengthof(param))
{ {
if (filename != NULL) this->filename = strdup(filename); if (filename != NULL) this->filename = stredup(filename);
this->name->AddRef(); this->name->AddRef();
this->info->AddRef(); this->info->AddRef();
this->url->AddRef(); this->url->AddRef();
@ -78,7 +78,7 @@ GRFConfig::GRFConfig(const GRFConfig &config) :
{ {
MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum)); MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
MemCpyT<uint32>(this->param, config.param, lengthof(this->param)); MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
if (config.filename != NULL) this->filename = strdup(config.filename); if (config.filename != NULL) this->filename = stredup(config.filename);
this->name->AddRef(); this->name->AddRef();
this->info->AddRef(); this->info->AddRef();
this->url->AddRef(); this->url->AddRef();
@ -95,7 +95,7 @@ GRFConfig::GRFConfig(const GRFConfig &config) :
/** Cleanup a GRFConfig object. */ /** Cleanup a GRFConfig object. */
GRFConfig::~GRFConfig() GRFConfig::~GRFConfig()
{ {
/* GCF_COPY as in NOT strdupped/alloced the filename */ /* GCF_COPY as in NOT stredupped/alloced the filename */
if (!HasBit(this->flags, GCF_COPY)) { if (!HasBit(this->flags, GCF_COPY)) {
free(this->filename); free(this->filename);
delete this->error; delete this->error;
@ -204,8 +204,8 @@ GRFError::GRFError(const GRFError &error) :
message(error.message), message(error.message),
severity(error.severity) severity(error.severity)
{ {
if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message); if (error.custom_message != NULL) this->custom_message = stredup(error.custom_message);
if (error.data != NULL) this->data = strdup(error.data); if (error.data != NULL) this->data = stredup(error.data);
memcpy(this->param_value, error.param_value, sizeof(this->param_value)); memcpy(this->param_value, error.param_value, sizeof(this->param_value));
} }
@ -584,7 +584,7 @@ compatible_grf:
* already a local one, so there is no need to replace it. */ * already a local one, so there is no need to replace it. */
if (!HasBit(c->flags, GCF_COPY)) { if (!HasBit(c->flags, GCF_COPY)) {
free(c->filename); free(c->filename);
c->filename = strdup(f->filename); c->filename = stredup(f->filename);
memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum)); memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
c->name->Release(); c->name->Release();
c->name = f->name; c->name = f->name;

@ -2036,9 +2036,9 @@ struct ScanProgressWindow : public Window {
if (name == NULL) { if (name == NULL) {
char buf[256]; char buf[256];
GetString(buf, STR_NEWGRF_SCAN_ARCHIVES, lastof(buf)); GetString(buf, STR_NEWGRF_SCAN_ARCHIVES, lastof(buf));
this->last_name = strdup(buf); this->last_name = stredup(buf);
} else { } else {
this->last_name = strdup(name); this->last_name = stredup(name);
} }
this->scanned = num; this->scanned = num;
if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num; if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num;

@ -231,7 +231,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
/* In case of a (broken) NewGRF without a default, /* In case of a (broken) NewGRF without a default,
* assume an empty string. */ * assume an empty string. */
grfmsg(1, "choice list misses default value"); grfmsg(1, "choice list misses default value");
this->strings[0] = strdup(""); this->strings[0] = stredup("");
} }
char *d = old_d; char *d = old_d;

@ -726,7 +726,7 @@ CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
if (company != INVALID_OWNER && company != _local_company) return CommandCost(); if (company != INVALID_OWNER && company != _local_company) return CommandCost();
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
char *news = strdup(text); char *news = stredup(text);
SetDParamStr(0, news); SetDParamStr(0, news);
AddNewsItem(STR_NEWS_CUSTOM_ITEM, type, NF_NORMAL, reftype1, p2, NR_NONE, UINT32_MAX, news); AddNewsItem(STR_NEWS_CUSTOM_ITEM, type, NF_NORMAL, reftype1, p2, NR_NONE, UINT32_MAX, news);
} }

@ -444,7 +444,7 @@ struct AfterNewGRFScan : NewGRFScanCallback {
#if defined(ENABLE_NETWORK) #if defined(ENABLE_NETWORK)
if (dedicated_host != NULL) { if (dedicated_host != NULL) {
_network_bind_list.Clear(); _network_bind_list.Clear();
*_network_bind_list.Append() = strdup(dedicated_host); *_network_bind_list.Append() = stredup(dedicated_host);
} }
if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port; if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
#endif /* ENABLE_NETWORK */ #endif /* ENABLE_NETWORK */
@ -563,23 +563,23 @@ int openttd_main(int argc, char *argv[])
int i; int i;
while ((i = mgo.GetOpt()) != -1) { while ((i = mgo.GetOpt()) != -1) {
switch (i) { switch (i) {
case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break; case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break; case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
case 'M': free(music_set); music_set = strdup(mgo.opt); break; case 'M': free(music_set); music_set = stredup(mgo.opt); break;
case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break; case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break; case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
case 'v': free(videodriver); videodriver = strdup(mgo.opt); break; case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
case 'b': free(blitter); blitter = strdup(mgo.opt); break; case 'b': free(blitter); blitter = stredup(mgo.opt); break;
#if defined(ENABLE_NETWORK) #if defined(ENABLE_NETWORK)
case 'D': case 'D':
free(musicdriver); free(musicdriver);
free(sounddriver); free(sounddriver);
free(videodriver); free(videodriver);
free(blitter); free(blitter);
musicdriver = strdup("null"); musicdriver = stredup("null");
sounddriver = strdup("null"); sounddriver = stredup("null");
videodriver = strdup("dedicated"); videodriver = stredup("dedicated");
blitter = strdup("null"); blitter = stredup("null");
dedicated = true; dedicated = true;
SetDebugString("net=6"); SetDebugString("net=6");
if (mgo.opt != NULL) { if (mgo.opt != NULL) {
@ -667,7 +667,7 @@ int openttd_main(int argc, char *argv[])
goto exit_noshutdown; goto exit_noshutdown;
} }
case 'G': scanner->generation_seed = atoi(mgo.opt); break; case 'G': scanner->generation_seed = atoi(mgo.opt); break;
case 'c': _config_file = strdup(mgo.opt); break; case 'c': _config_file = stredup(mgo.opt); break;
case 'x': scanner->save_config = false; break; case 'x': scanner->save_config = false; break;
case 'h': case 'h':
i = -2; // Force printing of help. i = -2; // Force printing of help.
@ -739,7 +739,7 @@ int openttd_main(int argc, char *argv[])
InitWindowSystem(); InitWindowSystem();
BaseGraphics::FindSets(); BaseGraphics::FindSets();
if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set); if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
if (!BaseGraphics::SetSet(graphics_set)) { if (!BaseGraphics::SetSet(graphics_set)) {
if (!StrEmpty(graphics_set)) { if (!StrEmpty(graphics_set)) {
BaseGraphics::SetSet(NULL); BaseGraphics::SetSet(NULL);
@ -755,7 +755,7 @@ int openttd_main(int argc, char *argv[])
GfxInitPalettes(); GfxInitPalettes();
DEBUG(misc, 1, "Loading blitter..."); DEBUG(misc, 1, "Loading blitter...");
if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter); if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
_blitter_autodetected = StrEmpty(blitter); _blitter_autodetected = StrEmpty(blitter);
/* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */ /* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */
if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactory::SelectBlitter("32bpp-anim") == NULL) { if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
@ -767,7 +767,7 @@ int openttd_main(int argc, char *argv[])
} }
free(blitter); free(blitter);
if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver); if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
_video_driver = (VideoDriver*)DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO); _video_driver = (VideoDriver*)DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
if (_video_driver == NULL) { if (_video_driver == NULL) {
StrEmpty(videodriver) ? StrEmpty(videodriver) ?
@ -810,7 +810,7 @@ int openttd_main(int argc, char *argv[])
InitializeScreenshotFormats(); InitializeScreenshotFormats();
BaseSounds::FindSets(); BaseSounds::FindSets();
if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set); if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
if (!BaseSounds::SetSet(sounds_set)) { if (!BaseSounds::SetSet(sounds_set)) {
if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) { if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt."); usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
@ -823,7 +823,7 @@ int openttd_main(int argc, char *argv[])
free(sounds_set); free(sounds_set);
BaseMusic::FindSets(); BaseMusic::FindSets();
if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set); if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
if (!BaseMusic::SetSet(music_set)) { if (!BaseMusic::SetSet(music_set)) {
if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) { if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt."); usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
@ -835,7 +835,7 @@ int openttd_main(int argc, char *argv[])
} }
free(music_set); free(music_set);
if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver); if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
_sound_driver = (SoundDriver*)DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND); _sound_driver = (SoundDriver*)DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
if (_sound_driver == NULL) { if (_sound_driver == NULL) {
StrEmpty(sounddriver) ? StrEmpty(sounddriver) ?
@ -844,7 +844,7 @@ int openttd_main(int argc, char *argv[])
} }
free(sounddriver); free(sounddriver);
if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver); if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
_music_driver = (MusicDriver*)DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC); _music_driver = (MusicDriver*)DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
if (_music_driver == NULL) { if (_music_driver == NULL) {
StrEmpty(musicdriver) ? StrEmpty(musicdriver) ?
@ -1157,7 +1157,7 @@ void SwitchToMode(SwitchMode new_mode)
LoadIntroGame(); LoadIntroGame();
if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) { if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL); ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name); BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
} }
break; break;

@ -435,7 +435,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi
/* Convert the command line to UTF-8. We need a dedicated buffer /* Convert the command line to UTF-8. We need a dedicated buffer
* for this because argv[] points into this buffer and this needs to * for this because argv[] points into this buffer and this needs to
* be available between subsequent calls to FS2OTTD(). */ * be available between subsequent calls to FS2OTTD(). */
char *cmdline = strdup(FS2OTTD(GetCommandLine())); char *cmdline = stredup(FS2OTTD(GetCommandLine()));
#if defined(_DEBUG) #if defined(_DEBUG)
CreateConsole(); CreateConsole();
@ -498,7 +498,7 @@ void DetermineBasePaths(const char *exe)
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp)); strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_PERSONAL_DIR] = strdup(tmp); _searchpaths[SP_PERSONAL_DIR] = stredup(tmp);
} else { } else {
_searchpaths[SP_PERSONAL_DIR] = NULL; _searchpaths[SP_PERSONAL_DIR] = NULL;
} }
@ -508,7 +508,7 @@ void DetermineBasePaths(const char *exe)
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp)); strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_SHARED_DIR] = strdup(tmp); _searchpaths[SP_SHARED_DIR] = stredup(tmp);
} else { } else {
_searchpaths[SP_SHARED_DIR] = NULL; _searchpaths[SP_SHARED_DIR] = NULL;
} }
@ -520,7 +520,7 @@ void DetermineBasePaths(const char *exe)
/* Get the path to working directory of OpenTTD */ /* Get the path to working directory of OpenTTD */
getcwd(tmp, lengthof(tmp)); getcwd(tmp, lengthof(tmp));
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_WORKING_DIR] = strdup(tmp); _searchpaths[SP_WORKING_DIR] = stredup(tmp);
if (!GetModuleFileName(NULL, path, lengthof(path))) { if (!GetModuleFileName(NULL, path, lengthof(path))) {
DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError()); DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
@ -535,7 +535,7 @@ void DetermineBasePaths(const char *exe)
strecpy(tmp, convert_from_fs(exec_dir, tmp, lengthof(tmp)), lastof(tmp)); strecpy(tmp, convert_from_fs(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
char *s = strrchr(tmp, PATHSEPCHAR); char *s = strrchr(tmp, PATHSEPCHAR);
*(s + 1) = '\0'; *(s + 1) = '\0';
_searchpaths[SP_BINARY_DIR] = strdup(tmp); _searchpaths[SP_BINARY_DIR] = stredup(tmp);
} }
} }

@ -59,7 +59,7 @@ struct OskWindow : public Window {
this->querystrings[WID_OSK_TEXT] = this->qs; this->querystrings[WID_OSK_TEXT] = this->qs;
/* make a copy in case we need to reset later */ /* make a copy in case we need to reset later */
this->orig_str_buf = strdup(this->qs->text.buf); this->orig_str_buf = stredup(this->qs->text.buf);
this->InitNested(0); this->InitNested(0);
this->SetFocusedWidget(WID_OSK_TEXT); this->SetFocusedWidget(WID_OSK_TEXT);
@ -430,7 +430,7 @@ void UpdateOSKOriginalText(const Window *parent, int button)
if (osk == NULL || osk->parent != parent || osk->text_btn != button) return; if (osk == NULL || osk->parent != parent || osk->text_btn != button) return;
free(osk->orig_str_buf); free(osk->orig_str_buf);
osk->orig_str_buf = strdup(osk->qs->text.buf); osk->orig_str_buf = stredup(osk->qs->text.buf);
osk->SetDirty(); osk->SetDirty();
} }

@ -31,11 +31,11 @@
#define realloc SAFEGUARD_DO_NOT_USE_THIS_METHOD #define realloc SAFEGUARD_DO_NOT_USE_THIS_METHOD
/* Use stredup instead. */ /* Use stredup instead. */
//#define strdup SAFEGUARD_DO_NOT_USE_THIS_METHOD #define strdup SAFEGUARD_DO_NOT_USE_THIS_METHOD
#define strndup SAFEGUARD_DO_NOT_USE_THIS_METHOD #define strndup SAFEGUARD_DO_NOT_USE_THIS_METHOD
/* Use strecpy instead. */ /* Use strecpy instead. */
//#define strcpy SAFEGUARD_DO_NOT_USE_THIS_METHOD #define strcpy SAFEGUARD_DO_NOT_USE_THIS_METHOD
//#define strncpy SAFEGUARD_DO_NOT_USE_THIS_METHOD //#define strncpy SAFEGUARD_DO_NOT_USE_THIS_METHOD
/* Use strecat instead. */ /* Use strecat instead. */

@ -12,6 +12,7 @@
#include "../stdafx.h" #include "../stdafx.h"
#include "saveload_internal.h" #include "saveload_internal.h"
#include "../engine_base.h" #include "../engine_base.h"
#include "../string_func.h"
#include <map> #include <map>
#include "../safeguards.h" #include "../safeguards.h"
@ -107,7 +108,7 @@ void CopyTempEngineData()
e->preview_company = se->preview_company; e->preview_company = se->preview_company;
e->preview_wait = se->preview_wait; e->preview_wait = se->preview_wait;
e->company_avail = se->company_avail; e->company_avail = se->company_avail;
if (se->name != NULL) e->name = strdup(se->name); if (se->name != NULL) e->name = stredup(se->name);
} }
/* Get rid of temporary data */ /* Get rid of temporary data */

@ -153,7 +153,7 @@ static void Load_GSTR()
LanguageStrings *ls = new LanguageStrings(_game_saveload_string != NULL ? _game_saveload_string : ""); LanguageStrings *ls = new LanguageStrings(_game_saveload_string != NULL ? _game_saveload_string : "");
for (uint i = 0; i < _game_saveload_strings; i++) { for (uint i = 0; i < _game_saveload_strings; i++) {
SlObject(NULL, _game_language_string); SlObject(NULL, _game_language_string);
*ls->lines.Append() = strdup(_game_saveload_string != NULL ? _game_saveload_string : ""); *ls->lines.Append() = stredup(_game_saveload_string != NULL ? _game_saveload_string : "");
} }
*_current_data->raw_strings.Append() = ls; *_current_data->raw_strings.Append() = ls;

@ -527,11 +527,11 @@ void NORETURN SlError(StringID string, const char *extra_msg)
if (_sl.action == SLA_LOAD_CHECK) { if (_sl.action == SLA_LOAD_CHECK) {
_load_check_data.error = string; _load_check_data.error = string;
free(_load_check_data.error_data); free(_load_check_data.error_data);
_load_check_data.error_data = (extra_msg == NULL) ? NULL : strdup(extra_msg); _load_check_data.error_data = (extra_msg == NULL) ? NULL : stredup(extra_msg);
} else { } else {
_sl.error_str = string; _sl.error_str = string;
free(_sl.extra_msg); free(_sl.extra_msg);
_sl.extra_msg = (extra_msg == NULL) ? NULL : strdup(extra_msg); _sl.extra_msg = (extra_msg == NULL) ? NULL : stredup(extra_msg);
} }
/* We have to NULL all pointers here; we might be in a state where /* We have to NULL all pointers here; we might be in a state where

@ -94,10 +94,10 @@ char *CopyFromOldName(StringID id)
/* Terminate the new string and copy it back to the name array */ /* Terminate the new string and copy it back to the name array */
*strto = '\0'; *strto = '\0';
return strdup(tmp); return stredup(tmp);
} else { } else {
/* Name will already be in UTF-8. */ /* Name will already be in UTF-8. */
return strdup(&_old_name_array[LEN_OLD_STRINGS * GB(id, 0, 9)]); return stredup(&_old_name_array[LEN_OLD_STRINGS * GB(id, 0, 9)]);
} }
} }

@ -154,7 +154,7 @@ ScriptController::~ScriptController()
sq_newslot(vm, -3, SQFalse); sq_newslot(vm, -3, SQFalse);
sq_pop(vm, 1); sq_pop(vm, 1);
controller->loaded_library[strdup(library_name)] = strdup(fake_class); controller->loaded_library[stredup(library_name)] = stredup(fake_class);
} }
/* Find the real class inside the fake class (like 'sets.Vector') */ /* Find the real class inside the fake class (like 'sets.Vector') */

@ -12,6 +12,7 @@
#include "../../stdafx.h" #include "../../stdafx.h"
#include "script_error.hpp" #include "script_error.hpp"
#include "../../core/bitmath_func.hpp" #include "../../core/bitmath_func.hpp"
#include "../../string_func.h"
#include "../../safeguards.h" #include "../../safeguards.h"
@ -25,7 +26,7 @@ ScriptError::ScriptErrorMapString ScriptError::error_map_string = ScriptError::S
/* static */ char *ScriptError::GetLastErrorString() /* static */ char *ScriptError::GetLastErrorString()
{ {
return strdup((*error_map_string.find(ScriptError::GetLastError())).second); return stredup((*error_map_string.find(ScriptError::GetLastError())).second);
} }
/* static */ ScriptErrorType ScriptError::StringToError(StringID internal_string_id) /* static */ ScriptErrorType ScriptError::StringToError(StringID internal_string_id)

@ -17,6 +17,7 @@
#include "../../settings_type.h" #include "../../settings_type.h"
#include "../../engine_base.h" #include "../../engine_base.h"
#include "../../articulated_vehicles.h" #include "../../articulated_vehicles.h"
#include "../../string_func.h"
#include "table/strings.h" #include "table/strings.h"
#include "../../safeguards.h" #include "../../safeguards.h"
@ -119,6 +120,17 @@ bool ScriptEventCompanyAskMerger::AcceptMerger()
return ScriptObject::DoCommand(0, this->owner, 0, CMD_BUY_COMPANY); return ScriptObject::DoCommand(0, this->owner, 0, CMD_BUY_COMPANY);
} }
ScriptEventAdminPort::ScriptEventAdminPort(const char *json) :
ScriptEvent(ET_ADMIN_PORT),
json(stredup(json))
{
}
ScriptEventAdminPort::~ScriptEventAdminPort()
{
free(this->json);
}
#define SKIP_EMPTY(p) while (*(p) == ' ' || *(p) == '\n' || *(p) == '\r') (p)++; #define SKIP_EMPTY(p) while (*(p) == ' ' || *(p) == '\n' || *(p) == '\r') (p)++;
#define RETURN_ERROR(stack) { ScriptLog::Error("Received invalid JSON data from AdminPort."); if (stack != 0) sq_pop(vm, stack); return NULL; } #define RETURN_ERROR(stack) { ScriptLog::Error("Received invalid JSON data from AdminPort."); if (stack != 0) sq_pop(vm, stack); return NULL; }

@ -839,15 +839,8 @@ public:
/** /**
* @param json The JSON string which got sent. * @param json The JSON string which got sent.
*/ */
ScriptEventAdminPort(const char *json) : ScriptEventAdminPort(const char *json);
ScriptEvent(ET_ADMIN_PORT), ~ScriptEventAdminPort();
json(strdup(json))
{}
~ScriptEventAdminPort()
{
free(this->json);
}
/** /**
* Convert an ScriptEvent to the real instance. * Convert an ScriptEvent to the real instance.

@ -14,6 +14,7 @@
#include "../../core/alloc_func.hpp" #include "../../core/alloc_func.hpp"
#include "../../debug.h" #include "../../debug.h"
#include "../../window_func.h" #include "../../window_func.h"
#include "../../string_func.h"
#include "../../safeguards.h" #include "../../safeguards.h"
@ -53,7 +54,7 @@
/* Free last message, and write new message */ /* Free last message, and write new message */
free(log->lines[log->pos]); free(log->lines[log->pos]);
log->lines[log->pos] = strdup(message); log->lines[log->pos] = stredup(message);
log->type[log->pos] = level; log->type[log->pos] = level;
/* Cut string after first \n */ /* Cut string after first \n */

@ -264,7 +264,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
char buffer[64]; char buffer[64];
::GetString(buffer, string, lastof(buffer)); ::GetString(buffer, string, lastof(buffer));
::str_validate(buffer, lastof(buffer), SVS_NONE); ::str_validate(buffer, lastof(buffer), SVS_NONE);
return ::strdup(buffer); return ::stredup(buffer);
} }
/* static */ void ScriptObject::SetCallbackVariable(int index, int value) /* static */ void ScriptObject::SetCallbackVariable(int index, int value)

@ -19,6 +19,16 @@
#include "../../safeguards.h" #include "../../safeguards.h"
RawText::RawText(const char *text) : text(stredup(text))
{
}
RawText::~RawText()
{
free(this->text);
}
ScriptText::ScriptText(HSQUIRRELVM vm) : ScriptText::ScriptText(HSQUIRRELVM vm) :
ZeroedMemoryAllocator() ZeroedMemoryAllocator()
{ {
@ -73,7 +83,7 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm)
const SQChar *value; const SQChar *value;
sq_getstring(vm, -1, &value); sq_getstring(vm, -1, &value);
this->params[parameter] = strdup(SQ2OTTD(value)); this->params[parameter] = stredup(SQ2OTTD(value));
ValidateString(this->params[parameter]); ValidateString(this->params[parameter]);
break; break;
} }

@ -42,9 +42,8 @@ public:
*/ */
class RawText : public Text { class RawText : public Text {
public: public:
RawText(const char *text) : RawText(const char *text);
text(strdup(text)) {} ~RawText();
~RawText() { free(this->text); }
/* virtual */ const char *GetEncodedText() { return this->text; } /* virtual */ const char *GetEncodedText() { return this->text; }
private: private:

@ -21,7 +21,7 @@
void ScriptConfig::Change(const char *name, int version, bool force_exact_match, bool is_random) void ScriptConfig::Change(const char *name, int version, bool force_exact_match, bool is_random)
{ {
free(this->name); free(this->name);
this->name = (name == NULL) ? NULL : strdup(name); this->name = (name == NULL) ? NULL : stredup(name);
this->info = (name == NULL) ? NULL : this->FindInfo(this->name, version, force_exact_match); this->info = (name == NULL) ? NULL : this->FindInfo(this->name, version, force_exact_match);
this->version = (info == NULL) ? -1 : info->GetVersion(); this->version = (info == NULL) ? -1 : info->GetVersion();
this->is_random = is_random; this->is_random = is_random;
@ -45,14 +45,14 @@ void ScriptConfig::Change(const char *name, int version, bool force_exact_match,
ScriptConfig::ScriptConfig(const ScriptConfig *config) ScriptConfig::ScriptConfig(const ScriptConfig *config)
{ {
this->name = (config->name == NULL) ? NULL : strdup(config->name); this->name = (config->name == NULL) ? NULL : stredup(config->name);
this->info = config->info; this->info = config->info;
this->version = config->version; this->version = config->version;
this->config_list = NULL; this->config_list = NULL;
this->is_random = config->is_random; this->is_random = config->is_random;
for (SettingValueList::const_iterator it = config->settings.begin(); it != config->settings.end(); it++) { for (SettingValueList::const_iterator it = config->settings.begin(); it != config->settings.end(); it++) {
this->settings[strdup((*it).first)] = (*it).second; this->settings[stredup((*it).first)] = (*it).second;
} }
this->AddRandomDeviation(); this->AddRandomDeviation();
} }
@ -117,7 +117,7 @@ void ScriptConfig::SetSetting(const char *name, int value)
if (it != this->settings.end()) { if (it != this->settings.end()) {
(*it).second = value; (*it).second = value;
} else { } else {
this->settings[strdup(name)] = value; this->settings[stredup(name)] = value;
} }
} }
@ -160,7 +160,7 @@ int ScriptConfig::GetVersion() const
void ScriptConfig::StringToSettings(const char *value) void ScriptConfig::StringToSettings(const char *value)
{ {
char *value_copy = strdup(value); char *value_copy = stredup(value);
char *s = value_copy; char *s = value_copy;
while (s != NULL) { while (s != NULL) {

@ -83,9 +83,9 @@ bool ScriptInfo::CheckMethod(const char *name) const
} }
/* Get location information of the scanner */ /* Get location information of the scanner */
info->main_script = strdup(info->scanner->GetMainScript()); info->main_script = stredup(info->scanner->GetMainScript());
const char *tar_name = info->scanner->GetTarFile(); const char *tar_name = info->scanner->GetTarFile();
if (tar_name != NULL) info->tar_file = strdup(tar_name); if (tar_name != NULL) info->tar_file = stredup(tar_name);
/* Cache the data the info file gives us. */ /* Cache the data the info file gives us. */
if (!info->engine->CallStringMethodStrdup(*info->SQ_instance, "GetAuthor", &info->author, MAX_GET_OPS)) return SQ_ERROR; if (!info->engine->CallStringMethodStrdup(*info->SQ_instance, "GetAuthor", &info->author, MAX_GET_OPS)) return SQ_ERROR;
@ -133,7 +133,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
if (strcmp(key, "name") == 0) { if (strcmp(key, "name") == 0) {
const SQChar *sqvalue; const SQChar *sqvalue;
if (SQ_FAILED(sq_getstring(vm, -1, &sqvalue))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -1, &sqvalue))) return SQ_ERROR;
char *name = strdup(SQ2OTTD(sqvalue)); char *name = stredup(SQ2OTTD(sqvalue));
char *s; char *s;
ValidateString(name); ValidateString(name);
@ -146,7 +146,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
} else if (strcmp(key, "description") == 0) { } else if (strcmp(key, "description") == 0) {
const SQChar *sqdescription; const SQChar *sqdescription;
if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR;
config.description = strdup(SQ2OTTD(sqdescription)); config.description = stredup(SQ2OTTD(sqdescription));
ValidateString(config.description); ValidateString(config.description);
items |= 0x002; items |= 0x002;
} else if (strcmp(key, "min_value") == 0) { } else if (strcmp(key, "min_value") == 0) {
@ -264,8 +264,8 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
const char *label = SQ2OTTD(sq_label); const char *label = SQ2OTTD(sq_label);
ValidateString(label); ValidateString(label);
/* !Contains() prevents strdup from leaking. */ /* !Contains() prevents stredup from leaking. */
if (!config->labels->Contains(key)) config->labels->Insert(key, strdup(label)); if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label));
sq_pop(vm, 2); sq_pop(vm, 2);
} }

@ -29,12 +29,12 @@
bool ScriptScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename) bool ScriptScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
{ {
free(this->main_script); free(this->main_script);
this->main_script = strdup(filename); this->main_script = stredup(filename);
if (this->main_script == NULL) return false; if (this->main_script == NULL) return false;
free(this->tar_file); free(this->tar_file);
if (tar_filename != NULL) { if (tar_filename != NULL) {
this->tar_file = strdup(tar_filename); this->tar_file = stredup(tar_filename);
if (this->tar_file == NULL) return false; if (this->tar_file == NULL) return false;
} else { } else {
this->tar_file = NULL; this->tar_file = NULL;
@ -150,13 +150,13 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
return; return;
} }
this->info_list[strdup(script_name)] = info; this->info_list[stredup(script_name)] = info;
if (!info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) { if (!info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) {
/* Add the script to the 'unique' script list, where only the highest version /* Add the script to the 'unique' script list, where only the highest version
* of the script is registered. */ * of the script is registered. */
if (this->info_single_list.find(script_original_name) == this->info_single_list.end()) { if (this->info_single_list.find(script_original_name) == this->info_single_list.end()) {
this->info_single_list[strdup(script_original_name)] = info; this->info_single_list[stredup(script_original_name)] = info;
} else if (this->info_single_list[script_original_name]->GetVersion() < info->GetVersion()) { } else if (this->info_single_list[script_original_name]->GetVersion() < info->GetVersion()) {
this->info_single_list[script_original_name] = info; this->info_single_list[script_original_name] = info;
} }

@ -260,7 +260,7 @@ bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_nam
HSQOBJECT ret; HSQOBJECT ret;
if (!this->CallMethod(instance, method_name, &ret, suspend)) return false; if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
if (ret._type != OT_STRING) return false; if (ret._type != OT_STRING) return false;
*res = strdup(ObjectToString(&ret)); *res = stredup(ObjectToString(&ret));
ValidateString(*res); ValidateString(*res);
return true; return true;
} }

@ -26,7 +26,7 @@ template <class CL, ScriptType ST> const char *GetClassName();
namespace SQConvert { namespace SQConvert {
/** /**
* Pointers assigned to this class will be free'd when this instance * Pointers assigned to this class will be free'd when this instance
* comes out of scope. Useful to make sure you can use strdup(), * comes out of scope. Useful to make sure you can use stredup(),
* without leaking memory. * without leaking memory.
*/ */
struct SQAutoFreePointers : SmallVector<void *, 1> { struct SQAutoFreePointers : SmallVector<void *, 1> {
@ -113,7 +113,7 @@ namespace SQConvert {
const SQChar *tmp; const SQChar *tmp;
sq_getstring(vm, -1, &tmp); sq_getstring(vm, -1, &tmp);
char *tmp_str = strdup(SQ2OTTD(tmp)); char *tmp_str = stredup(SQ2OTTD(tmp));
sq_poptop(vm); sq_poptop(vm);
*ptr->Append() = (void *)tmp_str; *ptr->Append() = (void *)tmp_str;
str_validate(tmp_str, tmp_str + strlen(tmp_str)); str_validate(tmp_str, tmp_str + strlen(tmp_str));

@ -16,11 +16,13 @@
#include "squirrel_std.hpp" #include "squirrel_std.hpp"
#include "../core/alloc_func.hpp" #include "../core/alloc_func.hpp"
#include "../core/math_func.hpp" #include "../core/math_func.hpp"
#include "../string_func.h"
/* Due to the different characters for Squirrel, the scstrcat might be a simple /* Due to the different characters for Squirrel, the scstrcat might be a simple
* strcat which triggers the safeguard. But it isn't always a simple strcat. */ * strcat which triggers the safeguard. But it isn't always a simple strcat. */
#include "../safeguards.h" #include "../safeguards.h"
#undef strcat #undef strcat
#undef strdup
SQInteger SquirrelStd::min(HSQUIRRELVM vm) SQInteger SquirrelStd::min(HSQUIRRELVM vm)
@ -71,7 +73,7 @@ SQInteger SquirrelStd::require(HSQUIRRELVM vm)
real_filename = ReallocT(real_filename, scstrlen(real_filename) + scstrlen(filename) + 1); real_filename = ReallocT(real_filename, scstrlen(real_filename) + scstrlen(filename) + 1);
scstrcat(real_filename, filename); scstrcat(real_filename, filename);
/* Tars dislike opening files with '/' on Windows.. so convert it to '\\' ;) */ /* Tars dislike opening files with '/' on Windows.. so convert it to '\\' ;) */
char *filen = strdup(SQ2OTTD(real_filename)); char *filen = stredup(SQ2OTTD(real_filename));
#if (PATHSEPCHAR != '/') #if (PATHSEPCHAR != '/')
for (char *n = filen; *n != '\0'; n++) if (*n == '/') *n = PATHSEPCHAR; for (char *n = filen; *n != '\0'; n++) if (*n == '/') *n = PATHSEPCHAR;
#endif #endif

@ -532,7 +532,7 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
case SLE_VAR_STR: case SLE_VAR_STR:
case SLE_VAR_STRQ: case SLE_VAR_STRQ:
free(*(char**)ptr); free(*(char**)ptr);
*(char**)ptr = p == NULL ? NULL : strdup((const char*)p); *(char**)ptr = p == NULL ? NULL : stredup((const char*)p);
break; break;
case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break; case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break;
@ -687,7 +687,7 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
/* The value is different, that means we have to write it to the ini */ /* The value is different, that means we have to write it to the ini */
free(item->value); free(item->value);
item->value = strdup(buf); item->value = stredup(buf);
} }
} }
@ -709,7 +709,7 @@ static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *li
list->Clear(); list->Clear();
for (const IniItem *item = group->item; item != NULL; item = item->next) { for (const IniItem *item = group->item; item != NULL; item = item->next) {
if (item->name != NULL) *list->Append() = strdup(item->name); if (item->name != NULL) *list->Append() = stredup(item->name);
} }
} }
@ -1659,7 +1659,7 @@ void GetGRFPresetList(GRFPresetList *list)
IniGroup *group; IniGroup *group;
for (group = ini->group; group != NULL; group = group->next) { for (group = ini->group; group != NULL; group = group->next) {
if (strncmp(group->name, "preset-", 7) == 0) { if (strncmp(group->name, "preset-", 7) == 0) {
*list->Append() = strdup(group->name + 7); *list->Append() = stredup(group->name + 7);
} }
} }
@ -1929,7 +1929,7 @@ bool SetSettingValue(uint index, const char *value, bool force_newgame)
if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) { if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save); char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
free(*var); free(*var);
*var = strcmp(value, "(null)") == 0 ? NULL : strdup(value); *var = strcmp(value, "(null)") == 0 ? NULL : stredup(value);
} else { } else {
char *var = (char*)GetVariableAddress(NULL, &sd->save); char *var = (char*)GetVariableAddress(NULL, &sd->save);
strecpy(var, value, &var[sd->save.length - 1]); strecpy(var, value, &var[sd->save.length - 1]);

@ -460,7 +460,7 @@ struct GameOptionsWindow : Window {
const char *name = T::GetSet(index)->name; const char *name = T::GetSet(index)->name;
free(T::ini_set); free(T::ini_set);
T::ini_set = strdup(name); T::ini_set = stredup(name);
T::SetSet(name); T::SetSet(name);
this->reload = true; this->reload = true;

@ -55,7 +55,7 @@ CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
si->y = y; si->y = y;
si->z = GetSlopePixelZ(x, y); si->z = GetSlopePixelZ(x, y);
if (!StrEmpty(text)) { if (!StrEmpty(text)) {
si->name = strdup(text); si->name = stredup(text);
} }
si->UpdateVirtCoord(); si->UpdateVirtCoord();
InvalidateWindowData(WC_SIGN_LIST, 0, 0); InvalidateWindowData(WC_SIGN_LIST, 0, 0);
@ -90,7 +90,7 @@ CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Delete the old name */ /* Delete the old name */
free(si->name); free(si->name);
/* Assign the new one */ /* Assign the new one */
si->name = strdup(text); si->name = stredup(text);
if (_game_mode != GM_EDITOR) si->owner = _current_company; if (_game_mode != GM_EDITOR) si->owner = _current_company;
si->UpdateVirtCoord(); si->UpdateVirtCoord();

@ -3727,7 +3727,7 @@ CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
free(st->name); free(st->name);
st->name = reset ? NULL : strdup(text); st->name = reset ? NULL : stredup(text);
st->UpdateVirtCoord(); st->UpdateVirtCoord();
InvalidateWindowData(WC_STATION_LIST, st->owner, 1); InvalidateWindowData(WC_STATION_LIST, st->owner, 1);

@ -281,7 +281,7 @@
#endif #endif
#if defined(WINCE) #if defined(WINCE)
#define strdup _strdup #define stredup _stredup
#endif /* WINCE */ #endif /* WINCE */
/* NOTE: the string returned by these functions is only valid until the next /* NOTE: the string returned by these functions is only valid until the next

@ -81,10 +81,10 @@ static void UpdateElement(StoryPageElement &pe, TileIndex tile, uint32 reference
{ {
switch (pe.type) { switch (pe.type) {
case SPET_TEXT: case SPET_TEXT:
pe.text = strdup(text); pe.text = stredup(text);
break; break;
case SPET_LOCATION: case SPET_LOCATION:
pe.text = strdup(text); pe.text = stredup(text);
pe.referenced_id = tile; pe.referenced_id = tile;
break; break;
case SPET_GOAL: case SPET_GOAL:
@ -126,7 +126,7 @@ CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (StrEmpty(text)) { if (StrEmpty(text)) {
s->title = NULL; s->title = NULL;
} else { } else {
s->title = strdup(text); s->title = stredup(text);
} }
InvalidateWindowClassesData(WC_STORY_BOOK, -1); InvalidateWindowClassesData(WC_STORY_BOOK, -1);
@ -243,7 +243,7 @@ CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1,
if (StrEmpty(text)) { if (StrEmpty(text)) {
p->title = NULL; p->title = NULL;
} else { } else {
p->title = strdup(text); p->title = stredup(text);
} }
InvalidateWindowClassesData(WC_STORY_BOOK, page_id); InvalidateWindowClassesData(WC_STORY_BOOK, page_id);

@ -247,7 +247,7 @@ struct FileWriter {
*/ */
FileWriter(const char *filename) FileWriter(const char *filename)
{ {
this->filename = strdup(filename); this->filename = stredup(filename);
this->fh = fopen(this->filename, "wb"); this->fh = fopen(this->filename, "wb");
if (this->fh == NULL) { if (this->fh == NULL) {
@ -285,7 +285,7 @@ struct HeaderFileWriter : HeaderWriter, FileWriter {
* @param filename The file to open. * @param filename The file to open.
*/ */
HeaderFileWriter(const char *filename) : FileWriter("tmp.xxx"), HeaderFileWriter(const char *filename) : FileWriter("tmp.xxx"),
real_filename(strdup(filename)), prev(0) real_filename(stredup(filename)), prev(0)
{ {
fprintf(this->fh, "/* This file is automatically generated. Do not modify */\n\n"); fprintf(this->fh, "/* This file is automatically generated. Do not modify */\n\n");
fprintf(this->fh, "#ifndef TABLE_STRINGS_H\n"); fprintf(this->fh, "#ifndef TABLE_STRINGS_H\n");

@ -40,7 +40,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
* @param next The next chained case. * @param next The next chained case.
*/ */
Case::Case(int caseidx, const char *string, Case *next) : Case::Case(int caseidx, const char *string, Case *next) :
caseidx(caseidx), string(strdup(string)), next(next) caseidx(caseidx), string(stredup(string)), next(next)
{ {
} }
@ -59,7 +59,7 @@ Case::~Case()
* @param line The line this string was found on. * @param line The line this string was found on.
*/ */
LangString::LangString(const char *name, const char *english, int index, int line) : LangString::LangString(const char *name, const char *english, int index, int line) :
name(strdup(name)), english(strdup(english)), translated(NULL), name(stredup(name)), english(stredup(english)), translated(NULL),
hash_next(0), index(index), line(line), translated_case(NULL) hash_next(0), index(index), line(line), translated_case(NULL)
{ {
} }
@ -577,7 +577,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
* @param translation Are we reading a translation? * @param translation Are we reading a translation?
*/ */
StringReader::StringReader(StringData &data, const char *file, bool master, bool translation) : StringReader::StringReader(StringData &data, const char *file, bool master, bool translation) :
data(data), file(strdup(file)), master(master), translation(translation) data(data), file(stredup(file)), master(master), translation(translation)
{ {
} }
@ -614,7 +614,7 @@ static void ExtractCommandString(ParsedCommandStruct *p, const char *s, bool war
} else if (!(ar->flags & C_DONTCOUNT)) { // Ignore some of them } else if (!(ar->flags & C_DONTCOUNT)) { // Ignore some of them
if (p->np >= lengthof(p->pairs)) strgen_fatal("too many commands in string, max " PRINTF_SIZE, lengthof(p->pairs)); if (p->np >= lengthof(p->pairs)) strgen_fatal("too many commands in string, max " PRINTF_SIZE, lengthof(p->pairs));
p->pairs[p->np].a = ar; p->pairs[p->np].a = ar;
p->pairs[p->np].v = param[0] != '\0' ? strdup(param) : ""; p->pairs[p->np].v = param[0] != '\0' ? stredup(param) : "";
p->np++; p->np++;
} }
} }
@ -778,7 +778,7 @@ void StringReader::HandleString(char *str)
if (casep != NULL) { if (casep != NULL) {
ent->translated_case = new Case(ResolveCaseName(casep, strlen(casep)), s, ent->translated_case); ent->translated_case = new Case(ResolveCaseName(casep, strlen(casep)), s, ent->translated_case);
} else { } else {
ent->translated = strdup(s); ent->translated = stredup(s);
/* If the string was translated, use the line from the /* If the string was translated, use the line from the
* translated language so errors in the translated file * translated language so errors in the translated file
* are properly referenced to. */ * are properly referenced to. */

@ -165,7 +165,7 @@ void CopyOutDParam(uint64 *dst, const char **strings, StringID string, int num)
MemCpyT(dst, _global_string_params.GetPointerToOffset(0), num); MemCpyT(dst, _global_string_params.GetPointerToOffset(0), num);
for (int i = 0; i < num; i++) { for (int i = 0; i < num; i++) {
if (_global_string_params.HasTypeInformation() && _global_string_params.GetTypeAtOffset(i) == SCC_RAW_STRING_POINTER) { if (_global_string_params.HasTypeInformation() && _global_string_params.GetTypeAtOffset(i) == SCC_RAW_STRING_POINTER) {
strings[i] = strdup((const char *)(size_t)_global_string_params.GetParam(i)); strings[i] = stredup((const char *)(size_t)_global_string_params.GetParam(i));
dst[i] = (size_t)strings[i]; dst[i] = (size_t)strings[i];
} else { } else {
strings[i] = NULL; strings[i] = NULL;
@ -889,7 +889,7 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
sub_args.SetParam(i++, param); sub_args.SetParam(i++, param);
} else { } else {
char *g = strdup(s); char *g = stredup(s);
g[p - s] = '\0'; g[p - s] = '\0';
sub_args_need_free[i] = true; sub_args_need_free[i] = true;
@ -2124,7 +2124,7 @@ void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
* properly we have to set the colour of the string, otherwise we end up with a lot of artifacts. * properly we have to set the colour of the string, otherwise we end up with a lot of artifacts.
* The colour 'character' might change in the future, so for safety we just Utf8 Encode it into * The colour 'character' might change in the future, so for safety we just Utf8 Encode it into
* the string, which takes exactly three characters, so it replaces the "XXX" with the colour marker. */ * the string, which takes exactly three characters, so it replaces the "XXX" with the colour marker. */
static char *err_str = strdup("XXXThe current font is missing some of the characters used in the texts for this language. Read the readme to see how to solve this."); static char *err_str = stredup("XXXThe current font is missing some of the characters used in the texts for this language. Read the readme to see how to solve this.");
Utf8Encode(err_str, SCC_YELLOW); Utf8Encode(err_str, SCC_YELLOW);
SetDParamStr(0, err_str); SetDParamStr(0, err_str);
ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_WARNING); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_WARNING);
@ -2152,7 +2152,7 @@ void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
* the colour marker. * the colour marker.
*/ */
if (_current_text_dir != TD_LTR) { if (_current_text_dir != TD_LTR) {
static char *err_str = strdup("XXXThis version of OpenTTD does not support right-to-left languages. Recompile with icu enabled."); static char *err_str = stredup("XXXThis version of OpenTTD does not support right-to-left languages. Recompile with icu enabled.");
Utf8Encode(err_str, SCC_YELLOW); Utf8Encode(err_str, SCC_YELLOW);
SetDParamStr(0, err_str); SetDParamStr(0, err_str);
ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);

@ -24,6 +24,7 @@
#include "core/random_func.hpp" #include "core/random_func.hpp"
#include "game/game.hpp" #include "game/game.hpp"
#include "command_func.h" #include "command_func.h"
#include "string_func.h"
#include "table/strings.h" #include "table/strings.h"
@ -47,7 +48,7 @@ void Subsidy::AwardTo(CompanyID company)
SetDParam(0, company); SetDParam(0, company);
GetString(company_name, STR_COMPANY_NAME, lastof(company_name)); GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
char *cn = strdup(company_name); char *cn = stredup(company_name);
/* Add a news item */ /* Add a news item */
Pair reftype = SetupSubsidyDecodeParam(this, false); Pair reftype = SetupSubsidyDecodeParam(this, false);

@ -1705,7 +1705,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
old_generating_world.Restore(); old_generating_world.Restore();
if (t != NULL && !StrEmpty(text)) { if (t != NULL && !StrEmpty(text)) {
t->name = strdup(text); t->name = stredup(text);
t->UpdateVirtCoord(); t->UpdateVirtCoord();
} }
@ -1716,7 +1716,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
SetDParam(0, _current_company); SetDParam(0, _current_company);
GetString(company_name, STR_COMPANY_NAME, lastof(company_name)); GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
char *cn = strdup(company_name); char *cn = stredup(company_name);
SetDParamStr(0, cn); SetDParamStr(0, cn);
SetDParam(1, t->index); SetDParam(1, t->index);
@ -2448,7 +2448,7 @@ CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
free(t->name); free(t->name);
t->name = reset ? NULL : strdup(text); t->name = reset ? NULL : stredup(text);
t->UpdateVirtCoord(); t->UpdateVirtCoord();
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1); InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
@ -2525,7 +2525,7 @@ CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
free(t->text); free(t->text);
t->text = StrEmpty(text) ? NULL : strdup(text); t->text = StrEmpty(text) ? NULL : stredup(text);
InvalidateWindowData(WC_TOWN_VIEW, p1); InvalidateWindowData(WC_TOWN_VIEW, p1);
} }
@ -2742,7 +2742,7 @@ static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
SetDParam(0, _current_company); SetDParam(0, _current_company);
GetString(company_name, STR_COMPANY_NAME, lastof(company_name)); GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
char *cn = strdup(company_name); char *cn = stredup(company_name);
SetDParam(0, t->index); SetDParam(0, t->index);
SetDParamStr(1, cn); SetDParamStr(1, cn);

@ -751,7 +751,7 @@ static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
/* Check the name is unique. */ /* Check the name is unique. */
if (IsUniqueVehicleName(buf)) { if (IsUniqueVehicleName(buf)) {
dst->name = strdup(buf); dst->name = stredup(buf);
break; break;
} }
} }
@ -1029,7 +1029,7 @@ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
free(v->name); free(v->name);
v->name = reset ? NULL : strdup(text); v->name = reset ? NULL : stredup(text);
InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1); InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
MarkWholeScreenDirty(); MarkWholeScreenDirty();
} }

@ -622,7 +622,7 @@ void cocoaSetApplicationBundleDir()
CFURLRef url = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()); CFURLRef url = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
if (CFURLGetFileSystemRepresentation(url, true, (unsigned char*)tmp, MAXPATHLEN)) { if (CFURLGetFileSystemRepresentation(url, true, (unsigned char*)tmp, MAXPATHLEN)) {
AppendPathSeparator(tmp, lastof(tmp)); AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_APPLICATION_BUNDLE_DIR] = strdup(tmp); _searchpaths[SP_APPLICATION_BUNDLE_DIR] = stredup(tmp);
} else { } else {
_searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL; _searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
} }

@ -416,7 +416,7 @@ CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
free(wp->name); free(wp->name);
wp->name = reset ? NULL : strdup(text); wp->name = reset ? NULL : stredup(text);
wp->UpdateVirtCoord(); wp->UpdateVirtCoord();
} }

Loading…
Cancel
Save