【发布时间】:2018-03-30 03:38:40
【问题描述】:
我可以释放一个指针,例如:
unsigned char *string1=NULL;
string1=malloc(4096);
在改变它的值之后:
*string1+=2;
free(string1) 可以识别相应的内存块在递增后释放(例如指向字符串的一部分),还是我需要保留原始指针值以用于释放目的?
例如,对于 C 语言中 Visual Basic 6 函数 LTrim 的实现,我需要将 **string 作为参数传递,但最后我将返回 *string+=string_offset_pointer 以开始超出任何空格/制表符。
我认为我在这里更改了指针,所以如果我这样做,我需要保留原始指针的副本以释放它。将非空白内容覆盖到字符串本身可能会更好,然后用 0 终止它,以避免需要额外的指针副本来释放内存:
void LTrim(unsigned char **string)
{
unsigned long string_length;
unsigned long string_offset_pointer=0;
if(*string==NULL)return;
string_length=strlen(*string);
if(string_length==0)return;
while(string_offset_pointer<string_length)
{
if(
*(*string+string_offset_pointer)!=' ' &&
*(*string+string_offset_pointer)!='\t'
)
{
break;
}
string_offset_pointer++;
}
*string+=string_offset_pointer;
}
最好让函数用它的子字符串覆盖字符串,但不改变指针的实际值以避免需要它的两个副本:
void LTrim(unsigned char **string)
{
unsigned long string_length;
unsigned long string_offset_pointer=0;
unsigned long string_offset_rebase=0;
if(*string==NULL)return;
string_length=strlen(*string);
if(string_length==0)return;
//Detect the first leftmost non-blank
//character:
///
while(string_offset_pointer<string_length)
{
if(
*(*string+string_offset_pointer)!=' ' &&
*(*string+string_offset_pointer)!='\t'
)
{
break;
}
string_offset_pointer++;
}
//Copy the non-blank spaces over the
//originally blank spaces at the beginning
//of the string, from the first non-blank
//character up to the string length:
///
while(string_offset_pointer<string_length)
{
*(*string+string_offset_rebase)=
*(*string+string_offset_pointer);
string_offset_rebase++;
string_offset_pointer++;
}
//Terminate the newly-copied substring
//with a null byte for an ASCIIZ string.
//If the string was fully blank we will
//just get an empty string:
///
*(*string+string_offset_rebase)=0;
//Free the now unused part of the
//string. It assumes that realloc()
//will keep the current contents of our
//memory buffers and will just truncate them,
//like in this case where we are requesting
//to shrink the buffer:
///
realloc(*string,strlen(*string)+1);
}
【问题讨论】:
-
你需要保留原来的指针值。
-
您在示例中没有更改 string1 的值
标签: c pointers memory-leaks