C:如何释放已分配字符串的初始部分?
C: How to free the initial section of an allocated string?
如何将字符串释放到特定点?例如,如果我有:
char *s = (char *)malloc(sizeof(char) * 21);
s[20] = '[=10=]';
int i = 0;
while (i < 21)
{
s[i] = i + 'a';
i++;
}
然后我在某个时候切断了字符串并存储了那一半:
*(s + 10) = '[=11=]';
char *m = s + 11;
有没有办法将 s
释放到 s + 10
或第一个 [=14=]
?
Is there a way to free s
up to s + 10
or the first [=12=]
?
没有。至少不在标准库中。
有realloc
,但不保证"free s
up to s + 10
or the first [=12=]
"。
由于s
已经被系统分配了,你可以对其进行realloc
来缩小尺寸:
s = realloc(s, 11);
但是您不能在不释放其余区域的情况下释放已分配区域的开始,这是您做不到的。使用 memmove
和 realloc
移动数据并随后减小大小。
尝试 free
未分配的指针,或分配的指针加上偏移量会导致未定义的行为。
你可以这样做(正如你自己建议的那样,但问题已解决:)):
char *c = strdup(s + 10);
free(s);
s = c;
所以现在 s
指向字符串的末尾。
没有strdup
但仅使用标准函数的替代方案(有忘记空终止字符的风险):
char *c = malloc(strlen(s) - 10 + 1);
strcpy(c,s + 10);
free(s);
s = c;
和我一开始暗示的 memmove
解决方案(避免 allocate/free 但 offset/size 更难计算):
int offset = 10;
int size = strlen(s) - offset;
memmove(s,s+offset,size);
s[size]='[=13=]'; // null-terminate
s = realloc(s,size+1); // adjust size after null-termination
如何将字符串释放到特定点?例如,如果我有:
char *s = (char *)malloc(sizeof(char) * 21);
s[20] = '[=10=]';
int i = 0;
while (i < 21)
{
s[i] = i + 'a';
i++;
}
然后我在某个时候切断了字符串并存储了那一半:
*(s + 10) = '[=11=]';
char *m = s + 11;
有没有办法将 s
释放到 s + 10
或第一个 [=14=]
?
Is there a way to free
s
up tos + 10
or the first[=12=]
?
没有。至少不在标准库中。
有realloc
,但不保证"free s
up to s + 10
or the first [=12=]
"。
由于s
已经被系统分配了,你可以对其进行realloc
来缩小尺寸:
s = realloc(s, 11);
但是您不能在不释放其余区域的情况下释放已分配区域的开始,这是您做不到的。使用 memmove
和 realloc
移动数据并随后减小大小。
尝试 free
未分配的指针,或分配的指针加上偏移量会导致未定义的行为。
你可以这样做(正如你自己建议的那样,但问题已解决:)):
char *c = strdup(s + 10);
free(s);
s = c;
所以现在 s
指向字符串的末尾。
没有strdup
但仅使用标准函数的替代方案(有忘记空终止字符的风险):
char *c = malloc(strlen(s) - 10 + 1);
strcpy(c,s + 10);
free(s);
s = c;
和我一开始暗示的 memmove
解决方案(避免 allocate/free 但 offset/size 更难计算):
int offset = 10;
int size = strlen(s) - offset;
memmove(s,s+offset,size);
s[size]='[=13=]'; // null-terminate
s = realloc(s,size+1); // adjust size after null-termination