简体   繁体   English

附加字符后无法释放已分配的字符串内存

[英]Can't free an allocated string memory after appending character

I am trying to append a character to a string... that works fine unfortunately I can't free the mem of the string afterwards which causes that the string gets longer and longer.... as it reads a file every linie will be added to the string which obviously shouldn't happen 我试图将一个字符附加到一个字符串...这很好,但不幸的是我之后无法释放字符串的mem会导致字符串变得越来越长....因为它读取每个linie的文件将是添加到字符串显然不应该发生

char* append_char(char* string, char character)
{
        int length = strlen(string);
        string[length] = character;
        string[length+1] = '\0';
        return string;
}

I allocated mem for string like 我为字符串分配了mem

char *read_string = (char *)malloc(sizeof(char)*500);

call the function append_char(read_string,buffer[0]); 调用函数append_char(read_string,buffer[0]); and free it after the whole string is build free(read_string); 并在整个字符串构建free(read_string);后释放它free(read_string);

I presume that once I call the append_char() , the mem allocation is going to be changed, which cause that I can't get hold of it. 我假设一旦我调用append_char(),mem分配将被更改,这导致我无法掌握它。

Edited: here is the function which uses the append_char() 编辑:这是使用append_char()的函数

char *read_log_file_row(char *result,int t)
{
filepath ="//home/,,,,,/mmm.txt";
int max = sizeof(char)*2;
char buffer[max];
char *return_fgets;

char *read_string = malloc(sizeof(char)*500);

file_pointer = fopen(filepath,"r");

if(file_pointer == NULL)
{
    printf("Didn't work....");
    return NULL;
}   

int i = 0;

while(i<=t)
{
  while(return_fgets = (fgets(buffer, max, file_pointer)))
  {
    if(buffer[0] == '\n') 
    {
       ++i;
       break;   
    }   

        if(i==t)
    {
      append_char(read_string,buffer[0]);
     }      
   }

   if(return_fgets == NULL)
   {
      free(read_string);
      return NULL;                              
/*              return "\0";*/
        }
       if(buffer[0] != '\n') 
        append_char(read_string,buffer[0]);

   }    
   fclose(file_pointer);
    strcpy(result,read_string); 
    free(read_string);
   return result;
}
  1. Dont cast the return value of malloc() in C . 不要在C中malloc()的返回值
  2. Make sure you initialize read_string to an empty string before you try to append to it, by setting read_string[0] = '\\0'; 通过设置read_string[0] = '\\0';确保在尝试追加它之前将read_string初始化为空字符串read_string[0] = '\\0'; .
  3. Make sure you track the current length, so you don't try to build a string that won't fit in the buffer. 确保跟踪当前长度,因此不要尝试构建不适合缓冲区的字符串。 500 chars allocated means max string length is 499 characters. 分配500个字符表示最大字符串长度为499个字符。

Not sure what you expect should happen when you do free(read_string) . 不确定当你执行free(read_string)时你会发生什么。 It sounds (from your comment to @Steve Jessop's answer) that you do something like this: 听起来(从你的评论到@Steve Jessop的回答)你做了这样的事情:

char *read_string = malloc(500);
read_string[0] = '\0';  /* Let's assume you do this. */
append_char(read_string, 'a'); /* Or whatever, many of these. */
free(read_string);
print("%c\n", *read_string); /* This invokes UNDEFINED BEHAVIOR. */

This might print an a , but that proves nothing since by doing this (accessing memory that has been free() :d) your program is invoking undefined behavior , which means that anything could happen. 可能会打印一个a ,但是这样做没有证明这一点(访问已经free()内存:d)你的程序正在调用未定义的行为 ,这意味着任何事情都可能发生。 You cannot draw conclusions from this, since the "test" is not valid. 无法从中得出结论,因为“测试”是无效的。 You can't free memory and then access it. 你不能释放内存然后访问它。 If you do it, and get some "reasonable"/"correct" result, you still cannot say that the free() :ing "didn't work". 如果你这样做,并得到一些“合理的”/“正确”的结果,你仍然不能说free() :ing“不起作用”。

No, the memory allocation is not changed in any way by append_char . 不, append_char不会以任何方式更改内存分配。 All it does is change the contents of the allocation -- by moving the nul terminator one byte along, you now care about the contents of one more of your 500 bytes than you did before. 它所做的只是更改分配的内容 - 通过将nul终结符移动一个字节,您现在关心的是您的500字节中的一个以上的内容。

If the string gets longer than 500 bytes (including terminator), then you have undefined behavior. 如果字符串超过500个字节(包括终结符),那么您有未定义的行为。 If you call strlen on something that isn't a nul-terminated string , for example if you pass it a pointer to uninitialized memory straight from malloc , then you have undefined behavior. 如果你对不是以空字符串结尾的字符串调用strlen ,例如,如果你直接从malloc传递一个指向未初始化内存的指针,那么你就有了未定义的行为。

Undefined behavior is bad[*]: feel free to read up on it, but "X has undefined behavior" is in effect a way of saying "you must not do X". 未定义的行为很糟糕[*]:随意阅读它,但“X有未定义的行为”实际上是一种说“你不能做X”的方式。

[*] To be precise: it's not guaranteed not to be bad... [*]确切地说:不能保证不坏......

Have you ever initialized the string? 你有没有初始化字符串? Try *read_string=0 after allocating it. 分配后尝试*read_string=0 Or use calloc . 或者使用calloc Also, have your string grown beyond the allocated memory? 还有,你的字符串增长超出分配的内存?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM