/* * This file is part of uIRCd. (https://git.redxen.eu/caskd/uIRCd) * Copyright (c) 2019, 2020 Alex-David Denes * * uIRCd is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * uIRCd is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with uIRCd. If not, see . */ #include "memory.h" #include "logging.h" #include // bool #include // fprintf() #include // malloc() free() #include // strcpy() /* Description: * This is a allocation manager that frees or allocates variables to pointers depending on the context. * If the pointer is already allocated it will free it and replace it with var * If var is NULL then the pointer is assigned NULL and left "undefined" * If it isn't NULL, the string var is copied to a allocated block stored in *ptr * NOTE: This could be expanded to have uses outside of strings but that's not required (yet) */ int allocate_copy(char** ptr, const char* const var) { if (var == NULL) LOG(LOG_DEBUG, "%s.", "Freeing pointer because provided variable has the address of NULL"); if (*ptr != NULL) LOG(LOG_DEBUG, "%s.", "Deallocating already allocated pointer for replacement"); free(*ptr); *ptr = NULL; if (var == NULL) return 1; if ((*ptr = (char*) malloc(sizeof(char) * (strlen(var) + 1))) != NULL) { strcpy(*ptr, var); return 1; } return 0; }