【问题标题】:Deallocating a String object释放字符串对象
【发布时间】:2016-06-30 20:57:56
【问题描述】:

我正在尝试编写一个函数,它是一个内存管理工具,它将释放 String 对象及其所有内容,这就是我到目前为止所写的,但似乎没有任何效果。谁能帮我改写我应该写的东西?我也不能使用 string.h。

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <inttypes.h>
#include <stdbool.h>

struct _String {
   char     *data;     // dynamically-allocated array to hold the characters
   uint32_t  length;   // number of characters in the string
};
typedef struct _String String;   

/** Deallocates a String object and all its content.
*
* Pre:
* **str is a proper String object
* **str was allocated dynamically
* Post:
* (**str).data has been deallocated
* **str has been deallocated
* *str == NULL
*/
void String_Dispose(String** str) {
    free(**(str).length);
    str->length = 0; 
    **str.data == NULL; 
    //free(str);
     *str == NULL;    
}

String_Dispose() 的调用如下所示:

String *pStr = malloc( sizeof(String) );
. . .
// Initialize the String and use it until we're done with it.

. . .

String_Dispose(&pStr);
// At this point, every trace of the String object is gone and pStr == NULL.

String_Dispose() 正在处理的String 对象一定是动态分配的,因为String_Dispose() 将尝试释放该对象。

【问题讨论】:

  • 这就是你所有的代码吗?如果可能,请发帖minimal reproducible example
  • 后缀 . 的优先级高于一元 *
  • 为什么要双重取消引用???显示分配代码。
  • @RSahu 是的,这就是我所拥有的,因为我不确定如何进一步处理。有什么建议吗?
  • 应该是(**str).data

标签: c pointers memory-management struct


【解决方案1】:

由于成员访问运算符 . 比解引用运算符 * 绑定更紧密,因此您需要使用:

void String_Dispose(String** str) {
    free((**str).data);

    // No need for these lines since you are planning on setting *str to NULL.
    // (**str).length = 0; 
    // (**str).data = NULL;   // Use =, not ==

    free(*str);
    *str = NULL;          // Use =, not ==
}

【讨论】:

  • 我用过这个,但是当我运行我的程序时它显示“Aborted (core dumped)”。任何想法为什么?
  • 作为基于您的更新的疯狂猜测:因为您没有分配 data 字段。
  • @EugeneSh。这是否意味着我会说 malloc(sizeof(data)); ?
  • 你不想要sizeof(data),你想要实际字符串的长度。
  • @Leah,不要把它当作咨询会议。这不是 SO 的目标。如果您还有其他问题,请发布一个包含更多详细信息的新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2019-09-16
相关资源
最近更新 更多