Codechange: Replace all usages of alloca/AllocaM with more modern/less discouraged alternatives

pull/544/head
Charles Pigott 3 years ago committed by PeterN
parent b19f42ecd9
commit b282664242

@ -9,6 +9,7 @@
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../core/alloc_func.hpp"
#include "address.h"
#include "../../safeguards.h"

@ -865,13 +865,11 @@ static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool us
if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
MemSetT(max_palette_offset, 0, num_building_sprites + 1);
std::vector<uint16> max_sprite_offset(num_building_sprites + 1, 0);
std::vector<uint16> max_palette_offset(num_building_sprites + 1, 0);
/* Groundsprite */
TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
if (_cur.skip_sprites < 0) return true;
if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
@ -886,7 +884,7 @@ static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool us
for (uint i = 0; i < num_building_sprites; i++) {
DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
if (_cur.skip_sprites < 0) return true;
if (flags & ~valid_flags) {
@ -5620,7 +5618,7 @@ static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
}
}
EngineID *engines = AllocaM(EngineID, idcount);
std::vector<EngineID> engines;
for (uint i = 0; i < idcount; i++) {
Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
if (e == nullptr) {
@ -5631,7 +5629,7 @@ static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
return;
}
engines[i] = e->index;
engines.push_back(e->index);
if (!wagover) last_engines[i] = engines[i];
}
@ -5679,9 +5677,10 @@ static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
{
CanalFeature *cfs = AllocaM(CanalFeature, idcount);
std::vector<CanalFeature> cfs;
cfs.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
cfs[i] = (CanalFeature)buf->ReadByte();
cfs.push_back((CanalFeature)buf->ReadByte());
}
uint8 cidcount = buf->ReadByte();
@ -5711,9 +5710,10 @@ static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *stations = AllocaM(uint8, idcount);
std::vector<uint8> stations;
stations.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
stations[i] = buf->ReadByte();
stations.push_back(buf->ReadByte());
}
uint8 cidcount = buf->ReadByte();
@ -5768,9 +5768,10 @@ static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *houses = AllocaM(uint8, idcount);
std::vector<uint8> houses;
houses.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
houses[i] = buf->ReadByte();
houses.push_back(buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -5799,9 +5800,10 @@ static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *industries = AllocaM(uint8, idcount);
std::vector<uint8> industries;
industries.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
industries[i] = buf->ReadByte();
industries.push_back(buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -5830,9 +5832,10 @@ static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *indtiles = AllocaM(uint8, idcount);
std::vector<uint8> indtiles;
indtiles.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
indtiles[i] = buf->ReadByte();
indtiles.push_back(buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -5856,9 +5859,10 @@ static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
{
CargoID *cargoes = AllocaM(CargoID, idcount);
std::vector<CargoID> cargoes;
cargoes.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
cargoes[i] = buf->ReadByte();
cargoes.push_back((CargoID)buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -5889,9 +5893,10 @@ static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *objects = AllocaM(uint8, idcount);
std::vector<uint8> objects;
objects.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
objects[i] = buf->ReadByte();
objects.push_back(buf->ReadByte());
}
uint8 cidcount = buf->ReadByte();
@ -5939,10 +5944,11 @@ static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
{
uint8 *railtypes = AllocaM(uint8, idcount);
std::vector<uint8> railtypes;
railtypes.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
uint8 id = buf->ReadByte();
railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE);
}
uint8 cidcount = buf->ReadByte();
@ -5972,10 +5978,11 @@ static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8 idcount, RoadTramType
{
RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
uint8 *roadtypes = AllocaM(uint8, idcount);
std::vector<uint8> roadtypes;
roadtypes.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
uint8 id = buf->ReadByte();
roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE);
}
uint8 cidcount = buf->ReadByte();
@ -6008,9 +6015,10 @@ static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *airports = AllocaM(uint8, idcount);
std::vector<uint8> airports;
airports.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
airports[i] = buf->ReadByte();
airports.push_back(buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -6039,9 +6047,10 @@ static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *airptiles = AllocaM(uint8, idcount);
std::vector<uint8> airptiles;
airptiles.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
airptiles[i] = buf->ReadByte();
airptiles.push_back(buf->ReadByte());
}
/* Skip the cargo type section, we only care about the default group */
@ -6070,9 +6079,10 @@ static void RoadStopMapSpriteGroup(ByteReader *buf, uint8 idcount)
return;
}
uint8 *roadstops = AllocaM(uint8, idcount);
std::vector<uint8> roadstops;
roadstops.reserve(idcount);
for (uint i = 0; i < idcount; i++) {
roadstops[i] = buf->ReadByte();
roadstops.push_back(buf->ReadByte());
}
uint8 cidcount = buf->ReadByte();
@ -9830,10 +9840,8 @@ static void FinalisePriceBaseMultipliers()
/* Evaluate grf overrides */
int num_grfs = (uint)_grf_files.size();
int *grf_overrides = AllocaM(int, num_grfs);
std::vector<int> grf_overrides(num_grfs, -1);
for (int i = 0; i < num_grfs; i++) {
grf_overrides[i] = -1;
GRFFile *source = _grf_files[i];
uint32 override = _grf_id_overrides[source->grfid];
if (override == 0) continue;

@ -81,8 +81,8 @@ bool LoadNewGRFSound(SoundEntry *sound)
if (file.ReadByte() != 0xFF) return false;
uint8 name_len = file.ReadByte();
char *name = AllocaM(char, name_len + 1);
file.ReadBlock(name, name_len + 1);
std::string name(name_len + 1, '\0');
file.ReadBlock(name.data(), name_len + 1);
/* Test string termination */
if (name[name_len] != 0) {

@ -124,22 +124,20 @@ struct DebugFileInfo {
SYSTEMTIME file_time;
};
static uint32 *_crc_table;
static uint32 _crc_table[256];
static void MakeCRCTable(uint32 *table)
static void MakeCRCTable()
{
uint32 crc, poly = 0xEDB88320L;
int i;
int j;
_crc_table = table;
for (i = 0; i != 256; i++) {
crc = i;
for (j = 8; j != 0; j--) {
crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1);
}
table[i] = crc;
_crc_table[i] = crc;
}
}
@ -206,7 +204,8 @@ static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
/* virtual */ char *CrashLogWindows::LogModules(char *output, const char *last) const
{
MakeCRCTable(AllocaM(uint32, 256));
MakeCRCTable();
output += seprintf(output, last, "Module information:\n");
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
@ -426,7 +425,8 @@ char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) c
memcpy(&ctx, ep->ContextRecord, sizeof(ctx));
/* Allocate space for symbol info. */
IMAGEHLP_SYMBOL64 *sym_info = (IMAGEHLP_SYMBOL64*)alloca(sizeof(IMAGEHLP_SYMBOL64) + MAX_SYMBOL_LEN - 1);
char sym_info_raw[sizeof(IMAGEHLP_SYMBOL64) + MAX_SYMBOL_LEN - 1];
IMAGEHLP_SYMBOL64 *sym_info = (IMAGEHLP_SYMBOL64*)sym_info_raw;
sym_info->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
sym_info->MaxNameLength = MAX_SYMBOL_LEN;
@ -698,7 +698,7 @@ static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARA
len += wcslen(convert_to_fs(CrashLogWindows::current->crashdump_filename, filenamebuf, lengthof(filenamebuf))) + 2;
len += wcslen(convert_to_fs(CrashLogWindows::current->screenshot_filename, filenamebuf, lengthof(filenamebuf))) + 1;
wchar_t *text = AllocaM(wchar_t, len);
static wchar_t text[lengthof(_crash_desc) + 3 * MAX_PATH * 2 + 7];
int printed = _snwprintf(text, len, _crash_desc, convert_to_fs(CrashLogWindows::current->crashlog_filename, filenamebuf, lengthof(filenamebuf)));
if (printed < 0 || (size_t)printed > len) {
MessageBox(wnd, L"Catastrophic failure trying to display crash message. Could not perform text formatting.", L"OpenTTD", MB_ICONERROR);
@ -729,7 +729,7 @@ static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARA
if (CrashLogWindows::current->WriteSavegame(filename, lastof(filename))) {
convert_to_fs(filename, filenamebuf, lengthof(filenamebuf));
size_t len = lengthof(_save_succeeded) + wcslen(filenamebuf) + 1;
wchar_t *text = AllocaM(wchar_t, len);
static wchar_t text[lengthof(_save_succeeded) + MAX_PATH * 2 + 1];
_snwprintf(text, len, _save_succeeded, filenamebuf);
MessageBox(wnd, text, L"Save successful", MB_ICONINFORMATION);
} else {

@ -71,7 +71,6 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
HKEY hKey;
LONG ret;
wchar_t vbuffer[MAX_PATH], dbuffer[256];
wchar_t *pathbuf;
const char *font_path;
uint index;
size_t path_len;
@ -122,12 +121,12 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
* contain multiple fonts inside this single file. GetFontData however
* returns the whole file, so we need to check each font inside to get the
* proper font. */
path_len = wcslen(vbuffer) + wcslen(dbuffer) + 2; // '\' and terminating nul.
pathbuf = AllocaM(wchar_t, path_len);
_snwprintf(pathbuf, path_len, L"%s\\%s", vbuffer, dbuffer);
std::wstring pathbuf(vbuffer);
pathbuf += L"\\";
pathbuf += dbuffer;
/* Convert the path into something that FreeType understands. */
font_path = GetShortPath(pathbuf);
font_path = GetShortPath(pathbuf.c_str());
index = 0;
do {
@ -374,7 +373,7 @@ void Win32FontCache::SetFontSize(FontSize fs, int pixels)
HGDIOBJ old = SelectObject(this->dc, temp);
UINT size = GetOutlineTextMetrics(this->dc, 0, nullptr);
LPOUTLINETEXTMETRIC otm = (LPOUTLINETEXTMETRIC)AllocaM(BYTE, size);
LPOUTLINETEXTMETRIC otm = (LPOUTLINETEXTMETRIC)new BYTE[size];
GetOutlineTextMetrics(this->dc, size, otm);
/* Font height is minimum height plus the difference between the default
@ -383,6 +382,7 @@ void Win32FontCache::SetFontSize(FontSize fs, int pixels)
/* Clamp() is not used as scaled_height could be greater than MAX_FONT_SIZE, which is not permitted in Clamp(). */
pixels = std::min(std::max(std::min<int>(otm->otmusMinimumPPEM, MAX_FONT_MIN_REC_SIZE) + diff, scaled_height), MAX_FONT_SIZE);
delete[] (BYTE*)otm;
SelectObject(dc, old);
DeleteObject(temp);
}
@ -405,7 +405,7 @@ void Win32FontCache::SetFontSize(FontSize fs, int pixels)
/* Query the font metrics we needed. */
UINT otmSize = GetOutlineTextMetrics(this->dc, 0, nullptr);
POUTLINETEXTMETRIC otm = (POUTLINETEXTMETRIC)AllocaM(BYTE, otmSize);
POUTLINETEXTMETRIC otm = (POUTLINETEXTMETRIC)new BYTE[otmSize];
GetOutlineTextMetrics(this->dc, otmSize, otm);
this->units_per_em = otm->otmEMSquare;
@ -418,6 +418,7 @@ void Win32FontCache::SetFontSize(FontSize fs, int pixels)
this->fontname = FS2OTTD((LPWSTR)((BYTE *)otm + (ptrdiff_t)otm->otmpFaceName));
Debug(fontcache, 2, "Loaded font '{}' with size {}", this->fontname, pixels);
delete[] (BYTE*)otm;
}
/**
@ -449,7 +450,7 @@ void Win32FontCache::ClearFontCache()
if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large");
/* Call GetGlyphOutline again with size to actually render the glyph. */
byte *bmp = AllocaM(byte, size);
byte *bmp = new byte[size];
GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, size, bmp, &mat);
/* GDI has rendered the glyph, now we allocate a sprite and copy the image into it. */
@ -498,6 +499,8 @@ void Win32FontCache::ClearFontCache()
this->SetGlyphPtr(key, &new_glyph);
delete[] bmp;
return new_glyph.sprite;
}
@ -589,10 +592,11 @@ void LoadWin32Font(FontSize fs)
/* Try to query an array of LOGFONTs that describe the file. */
DWORD len = 0;
if (GetFontResourceInfo(fontPath, &len, nullptr, 2) && len >= sizeof(LOGFONT)) {
LOGFONT *buf = (LOGFONT *)AllocaM(byte, len);
LOGFONT *buf = (LOGFONT *)new byte[len];
if (GetFontResourceInfo(fontPath, &len, buf, 2)) {
logfont = *buf; // Just use first entry.
}
delete[] (byte *)buf;
}
}

@ -544,10 +544,9 @@ std::string FS2OTTD(const std::wstring &name)
int name_len = (name.length() >= INT_MAX) ? INT_MAX : (int)name.length();
int len = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name_len, nullptr, 0, nullptr, nullptr);
if (len <= 0) return std::string();
char *utf8_buf = AllocaM(char, len + 1);
utf8_buf[len] = '\0';
WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name_len, utf8_buf, len, nullptr, nullptr);
return std::string(utf8_buf, static_cast<size_t>(len));
std::string utf8_buf(len, '\0'); // len includes terminating null
WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name_len, utf8_buf.data(), len, nullptr, nullptr);
return utf8_buf;
}
/**
@ -562,10 +561,9 @@ std::wstring OTTD2FS(const std::string &name)
int name_len = (name.length() >= INT_MAX) ? INT_MAX : (int)name.length();
int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), name_len, nullptr, 0);
if (len <= 0) return std::wstring();
wchar_t *system_buf = AllocaM(wchar_t, len + 1);
system_buf[len] = L'\0';
MultiByteToWideChar(CP_UTF8, 0, name.c_str(), name_len, system_buf, len);
return std::wstring(system_buf, static_cast<size_t>(len));
std::wstring system_buf(len, L'\0'); // len includes terminating null
MultiByteToWideChar(CP_UTF8, 0, name.c_str(), name_len, system_buf.data(), len);
return system_buf;
}
@ -669,13 +667,13 @@ int OTTDStringCompare(const char *s1, const char *s2)
int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2, -1, nullptr, 0);
if (len_s1 != 0 && len_s2 != 0) {
LPWSTR str_s1 = AllocaM(WCHAR, len_s1);
LPWSTR str_s2 = AllocaM(WCHAR, len_s2);
std::wstring str_s1(len_s1, L'\0'); // len includes terminating null
std::wstring str_s2(len_s2, L'\0');
MultiByteToWideChar(CP_UTF8, 0, s1, -1, str_s1, len_s1);
MultiByteToWideChar(CP_UTF8, 0, s2, -1, str_s2, len_s2);
MultiByteToWideChar(CP_UTF8, 0, s1, -1, str_s1.data(), len_s1);
MultiByteToWideChar(CP_UTF8, 0, s2, -1, str_s2.data(), len_s2);
int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1, -1, str_s2, -1, nullptr, nullptr, 0);
int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1.c_str(), -1, str_s2.c_str(), -1, nullptr, nullptr, 0);
if (result != 0) return result;
}
}

@ -1048,24 +1048,21 @@ static void SlStdString(void *ptr, VarType conv)
return;
}
char *buf = AllocaM(char, len + 1);
SlCopyBytes(buf, len);
buf[len] = '\0'; // properly terminate the string
str->resize(len + 1);
SlCopyBytes(str->data(), len);
(*str)[len] = '\0'; // properly terminate the string
StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
if ((conv & SLF_ALLOW_CONTROL) != 0) {
settings = settings | SVS_ALLOW_CONTROL_CODE;
if (IsSavegameVersionBefore(SLV_169)) {
str_fix_scc_encoded(buf, buf + len);
str_fix_scc_encoded(str->data(), str->data() + len);
}
}
if ((conv & SLF_ALLOW_NEWLINE) != 0) {
settings = settings | SVS_ALLOW_NEWLINE;
}
StrMakeValidInPlace(buf, buf + len, settings);
// Store sanitized string.
str->assign(buf);
*str = StrMakeValid(*str, settings);
}
case SLA_PTRS: break;

@ -182,8 +182,7 @@ static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *user
uint maxlines = Clamp(65536 / (w * pixelformat / 8), 16, 128); // number of lines per iteration
uint8 *buff = MallocT<uint8>(maxlines * w * pixelformat / 8); // buffer which is rendered to
uint8 *line = AllocaM(uint8, bytewidth); // one line, stored to file
memset(line, 0, bytewidth);
uint8 *line = CallocT<uint8>(bytewidth); // one line, stored to file
/* Start at the bottom, since bitmaps are stored bottom up */
do {
@ -211,6 +210,7 @@ static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *user
}
/* Write to file */
if (fwrite(line, bytewidth, 1, f) != 1) {
free(line);
free(buff);
fclose(f);
return false;
@ -218,6 +218,7 @@ static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *user
}
} while (h != 0);
free(line);
free(buff);
fclose(f);

@ -491,10 +491,11 @@ bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool
if (prepend_API_name) {
size_t len = strlen(class_name) + strlen(engine->GetAPIName()) + 1;
char *class_name2 = (char *)alloca(len);
char *class_name2 = MallocT<char>(len);
seprintf(class_name2, class_name2 + len - 1, "%s%s", engine->GetAPIName(), class_name);
sq_pushstring(vm, class_name2, -1);
free(class_name2);
} else {
sq_pushstring(vm, class_name, -1);
}

@ -1345,12 +1345,11 @@ StringList GetGRFPresetList()
*/
GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
{
size_t len = strlen(config_name) + 8;
char *section = (char*)alloca(len);
seprintf(section, section + len - 1, "preset-%s", config_name);
std::string section("preset-");
section += config_name;
ConfigIniFile ini(_config_file);
GRFConfig *config = GRFLoadConfig(ini, section, false);
GRFConfig *config = GRFLoadConfig(ini, section.c_str(), false);
return config;
}
@ -1363,12 +1362,11 @@ GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
*/
void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
{
size_t len = strlen(config_name) + 8;
char *section = (char*)alloca(len);
seprintf(section, section + len - 1, "preset-%s", config_name);
std::string section("preset-");
section += config_name;
ConfigIniFile ini(_config_file);
GRFSaveConfig(ini, section, config);
GRFSaveConfig(ini, section.c_str(), config);
ini.SaveToDisk(_config_file);
}
@ -1378,12 +1376,11 @@ void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
*/
void DeleteGRFPresetFromConfig(const char *config_name)
{
size_t len = strlen(config_name) + 8;
char *section = (char*)alloca(len);
seprintf(section, section + len - 1, "preset-%s", config_name);
std::string section("preset-");
section += config_name;
ConfigIniFile ini(_config_file);
ini.RemoveGroup(section);
ini.RemoveGroup(section.c_str());
ini.SaveToDisk(_config_file);
}

@ -426,7 +426,7 @@ static void *ReadRecolourSprite(SpriteFile &file, uint num)
byte *dest = (byte *)AllocSprite(std::max(RECOLOUR_SPRITE_SIZE, num));
if (file.NeedsPaletteRemap()) {
byte *dest_tmp = AllocaM(byte, std::max(RECOLOUR_SPRITE_SIZE, num));
byte *dest_tmp = new byte[std::max(RECOLOUR_SPRITE_SIZE, num)];
/* Only a few recolour sprites are less than 257 bytes */
if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
@ -436,6 +436,7 @@ static void *ReadRecolourSprite(SpriteFile &file, uint num)
for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
}
delete[] dest_tmp;
} else {
file.ReadBlock(dest, num);
}

@ -1387,7 +1387,6 @@ CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailTyp
if (flags & DC_EXEC) {
TileIndexDiff tile_delta;
byte *layout_ptr;
byte numtracks_orig;
Track track;
@ -1405,18 +1404,19 @@ CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailTyp
tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
track = AxisToTrack(axis);
layout_ptr = AllocaM(byte, numtracks * plat_len);
GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
std::vector<byte> layouts(numtracks * plat_len);
GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
numtracks_orig = numtracks;
Company *c = Company::Get(st->owner);
size_t layout_idx = 0;
TileIndex tile_track = tile_org;
do {
TileIndex tile = tile_track;
int w = plat_len;
do {
byte layout = *layout_ptr++;
byte layout = layouts[layout_idx++];
if (IsRailStationTile(tile) && HasStationReservation(tile)) {
/* Check for trains having a reservation for this tile. */
Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));

@ -362,7 +362,7 @@ char *ParseWord(char **buf)
/* Forward declaration */
static int TranslateArgumentIdx(int arg, int offset = 0);
static void EmitWordList(Buffer *buffer, const char * const *words, uint nw)
static void EmitWordList(Buffer *buffer, const std::vector<const char *> &words, uint nw)
{
buffer->AppendByte(nw);
for (uint i = 0; i < nw; i++) buffer->AppendByte((byte)strlen(words[i]) + 1);
@ -377,7 +377,7 @@ void EmitPlural(Buffer *buffer, char *buf, int value)
int argidx = _cur_argidx;
int offset = -1;
int expected = _plural_forms[_lang.plural_form].plural_count;
const char **words = AllocaM(const char *, std::max(expected, MAX_PLURALS));
std::vector<const char *> words(std::max(expected, MAX_PLURALS), nullptr);
int nw = 0;
/* Parse out the number, if one exists. Otherwise default to prev arg. */
@ -442,7 +442,7 @@ void EmitGender(Buffer *buffer, char *buf, int value)
buffer->AppendUtf8(SCC_GENDER_INDEX);
buffer->AppendByte(nw);
} else {
const char *words[MAX_NUM_GENDERS];
std::vector<const char *> words(MAX_NUM_GENDERS, nullptr);
/* This is a {G 0 foo bar two} command.
* If no relative number exists, default to +0 */
@ -947,11 +947,11 @@ void LanguageWriter::WriteLength(uint length)
*/
void LanguageWriter::WriteLang(const StringData &data)
{
uint *in_use = AllocaM(uint, data.tabs);
std::vector<uint> in_use;
for (size_t tab = 0; tab < data.tabs; tab++) {
uint n = data.CountInUse((uint)tab);
in_use[tab] = n;
in_use.push_back(n);
_lang.offsets[tab] = TO_LE16(n);
for (uint j = 0; j != in_use[tab]; j++) {

@ -580,7 +580,7 @@ static void HeightMapCurves(uint level)
float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
byte *c = AllocaM(byte, static_cast<size_t>(sx) * sy);
std::vector<byte> c(static_cast<size_t>(sx) * sy);
for (uint i = 0; i < sx * sy; i++) {
c[i] = Random() % lengthof(curve_maps);

@ -85,9 +85,9 @@ static bool CanDetermineTimeTaken(const Order *order, bool travelling)
* @param table Fill in arrival and departures including intermediate orders
* @param offset Add this value to result and all arrivals and departures
*/
static void FillTimetableArrivalDepartureTable(const Vehicle *v, VehicleOrderID start, bool travelling, TimetableArrivalDeparture *table, Ticks offset)
static void FillTimetableArrivalDepartureTable(const Vehicle *v, VehicleOrderID start, bool travelling, std::vector<TimetableArrivalDeparture> &table, Ticks offset)
{
assert(table != nullptr);
assert(!table.empty());
assert(v->GetNumOrders() >= 2);
assert(start < v->GetNumOrders());
@ -179,7 +179,7 @@ struct TimetableWindow : Window {
* @param table the table to fill
* @return if next arrival will be early
*/
static bool BuildArrivalDepartureList(const Vehicle *v, TimetableArrivalDeparture *table)
static bool BuildArrivalDepartureList(const Vehicle *v, std::vector<TimetableArrivalDeparture> &table)
{
assert(HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED));
@ -429,7 +429,7 @@ struct TimetableWindow : Window {
Ticks total_time = v->orders != nullptr ? v->orders->GetTimetableDurationIncomplete() : 0;
if (total_time <= 0 || v->GetNumOrders() <= 1 || !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) break;
TimetableArrivalDeparture *arr_dep = AllocaM(TimetableArrivalDeparture, v->GetNumOrders());
std::vector<TimetableArrivalDeparture> arr_dep(v->GetNumOrders());
const VehicleOrderID cur_order = v->cur_real_order_index % v->GetNumOrders();
VehicleOrderID earlyID = BuildArrivalDepartureList(v, arr_dep) ? cur_order : (VehicleOrderID)INVALID_VEH_ORDER_ID;

@ -1063,8 +1063,8 @@ char *GenerateTownNameString(char *buf, const char *last, size_t lang, uint32 se
const TownNameGeneratorParams *par = &_town_name_generators[lang];
if (last >= buf + par->min) return par->proc(buf, last, seed);
char *buffer = AllocaM(char, par->min + 1);
par->proc(buffer, buffer + par->min, seed);
std::string buffer(par->min + 1, '\0');
par->proc(buffer.data(), buffer.data() + par->min, seed);
return strecpy(buf, buffer, last);
return strecpy(buf, buffer.c_str(), last);
}

@ -328,9 +328,9 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
if (lParam & GCS_RESULTSTR) {
/* Read result string from the IME. */
LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
wchar_t *str = (wchar_t *)_alloca(len + sizeof(wchar_t));
len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str, len);
str[len / sizeof(wchar_t)] = '\0';
std::wstring str(len + 1, L'\0');
len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str.data(), len);
str[len / sizeof(wchar_t)] = L'\0';
/* Transmit text to windowing system. */
if (len > 0) {
@ -346,18 +346,18 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
if ((lParam & GCS_COMPSTR) && DrawIMECompositionString()) {
/* Read composition string from the IME. */
LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
wchar_t *str = (wchar_t *)_alloca(len + sizeof(wchar_t));
len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str, len);
str[len / sizeof(wchar_t)] = '\0';
std::wstring str(len + 1, L'\0');
len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str.data(), len);
str[len / sizeof(wchar_t)] = L'\0';
if (len > 0) {
static char utf8_buf[1024];
convert_from_fs(str, utf8_buf, lengthof(utf8_buf));
convert_from_fs(str.c_str(), utf8_buf, lengthof(utf8_buf));
/* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);
const char *caret = utf8_buf;
for (const wchar_t *c = str; *c != '\0' && *caret != '\0' && caret_bytes > 0; c++, caret_bytes--) {
for (const wchar_t *c = str.c_str(); *c != '\0' && *caret != '\0' && caret_bytes > 0; c++, caret_bytes--) {
/* Skip DBCS lead bytes or leading surrogates. */
if (Utf16IsLeadSurrogate(*c)) {
c++;
@ -1056,8 +1056,7 @@ bool VideoDriver_Win32GDI::AllocateBackingStore(int w, int h, bool force)
if (!force && w == _screen.width && h == _screen.height) return false;
BITMAPINFO *bi = (BITMAPINFO *)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
BITMAPINFO *bi = (BITMAPINFO *)new char[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256]();
bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi->bmiHeader.biWidth = this->width = w;
@ -1071,7 +1070,10 @@ bool VideoDriver_Win32GDI::AllocateBackingStore(int w, int h, bool force)
HDC dc = GetDC(0);
this->dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->buffer_bits, nullptr, 0);
if (this->dib_sect == nullptr) usererror("CreateDIBSection failed");
if (this->dib_sect == nullptr) {
delete[] bi;
usererror("CreateDIBSection failed");
}
ReleaseDC(0, dc);
_screen.width = w;
@ -1079,6 +1081,7 @@ bool VideoDriver_Win32GDI::AllocateBackingStore(int w, int h, bool force)
_screen.height = h;
_screen.dst_ptr = this->GetVideoPointer();
delete[] bi;
return true;
}
@ -1092,7 +1095,7 @@ void VideoDriver_Win32GDI::MakePalette()
{
CopyPalette(_local_palette, true);
LOGPALETTE *pal = (LOGPALETTE*)alloca(sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY));
LOGPALETTE *pal = (LOGPALETTE *)new char[sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY)]();
pal->palVersion = 0x300;
pal->palNumEntries = 256;
@ -1105,6 +1108,7 @@ void VideoDriver_Win32GDI::MakePalette()
}
this->gdi_palette = CreatePalette(pal);
delete[] pal;
if (this->gdi_palette == nullptr) usererror("CreatePalette failed!\n");
}

@ -264,7 +264,7 @@ CommandCost CmdBuildRailWaypoint(DoCommandFlag flags, TileIndex start_tile, Axis
wp->UpdateVirtCoord();
const StationSpec *spec = StationClass::Get(spec_class)->GetSpec(spec_index);
byte *layout_ptr = AllocaM(byte, count);
byte *layout_ptr = new byte[count];
if (spec == nullptr) {
/* The layout must be 0 for the 'normal' waypoints by design. */
memset(layout_ptr, 0, count);
@ -291,6 +291,7 @@ CommandCost CmdBuildRailWaypoint(DoCommandFlag flags, TileIndex start_tile, Axis
YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
}
DirtyCompanyInfrastructureWindows(wp->owner);
delete[] layout_ptr;
}
return cost;

Loading…
Cancel
Save