c - Using realloc to shrink the string inside struct -
i have small question using realloc function. assuming have:
typedef struct { char* location; int temp; int numberofrec; }temp; then declare pointer struct in main , allocate memory:
int main() { temp* data = xcalloc (1, sizeof(temp)); //wrapper function data->location = xcalloc (20, sizeof(char)); //wrapper function } now if reallocate memory data->location in function. need return address of temp* data?
int main() { somefunction(data); // use function or... //data = somefunction(data); ... } void somefunction(temp* data) { ... data->location = xrealloc (data->location, 10 * sizeof(char)); }
no. don't. because data pointer structure. whenever access element of structure through data using '->' operator, first de-referencing pointer.
for example,
data->location ==> (*data).location
also, when do,
data->location = xrealloc (data->location, 10 * sizeof(char));
if realloc fails, leaking memory , possibly invoking undefined behaviour (if don't include null pointer checks) because data->location has not been freed , assigned null since realloc returns null on failure.
i suggest following instead.
void *temp = null; temp = xrealloc (data->location, 10 * sizeof(char)); if(temp == null) { // realloc failed. free(data->location); data->location = null; } else { // continue data->location = temp; } i compiled minimal example you.
Comments
Post a Comment