【发布时间】: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