取消分配String对象

时间:2016-06-30 20:57:56

标签: c pointers memory-management struct

我正在尝试编写一个内存管理工具的函数,它将释放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对象String_Dispose()必须已动态分配,因为String_Dispose()将尝试解除分配该对象。

1 个答案:

答案 0 :(得分: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 ==
}