[英]Using realloc to shrink the string inside struct
I have a small question about using the realloc function. 关于使用realloc函数,我有一个小问题。 Assuming I have: 假设我有:
typedef struct
{
char* location;
int temp;
int numberOfRec;
}TEMP;
Then I declare a pointer to this struct in the main and allocate the memory: 然后,我在主机中声明一个指向该结构的指针并分配内存:
int main()
{
TEMP* data = xCalloc (1, sizeof(TEMP)); //wrapper function
data->location = xCalloc (20, sizeof(char)); //wrapper function
}
Now if I reallocate the memory for data->location in another function. 现在,如果我在另一个函数中为data-> location重新分配内存。 Do I need to return the address of TEMP* data? 我是否需要返回TEMP *数据的地址?
int main()
{
someFunction(data); // Use this function or...
//data = someFunction(data);
...
}
void someFunction(TEMP* data)
{
...
data->location = xRealloc (data->location, 10 * sizeof(char));
}
No. You don't. 不,你不知道 This is because data
is a pointer to the structure. 这是因为data
是指向结构的指针。 Whenever you access an element of the structure through data
using the '->' operator, you are first de-referencing the pointer. 每当您使用'->'运算符通过data
访问结构的元素时,都首先要取消引用指针。
For example, 例如,
data->location
==> (*data).location
data->location
==> (*data).location
Also, when you do, 而且,当您这样做时,
data->location = xRealloc (data->location, 10 * sizeof(char));
if the realloc fails, you would be leaking memory and possibly invoking undefined behaviour (if you don't include NULL pointer checks) because data->location
has not been free
d and it will be assigned to NULL since realloc
returns NULL on failure. 如果realloc失败,则可能会泄漏内存,并且可能会调用未定义的行为(如果不包括NULL指针检查),因为data->location
尚未free
d,并且由于realloc
在失败时返回NULL,因此它将分配给NULL。
I suggest you do the 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 a minimal example for you. 我为您编写了一个最小的示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.