Nor*_*tar 2 c memory arrays string memory-leaks
这似乎是一个愚蠢的问题,但我找不到答案。
\n无论如何,如果将字符串中的任意字符设置为 null,然后释放该字符串,是否会导致内存泄漏?
\n我想我对 free 函数如何工作的了解是有限的。
\n/*\n char *\n strchr(const char *s, int c);\n\n char *\n strrchr(const char *s, int c);\n\n The strchr() function locates the first occurrence of c (converted to a\n char) in the string pointed to by s. The terminating null character is\n considered part of the string; therefore if c is \xe2\x80\x98\\0\xe2\x80\x99, the functions\n locate the terminating \xe2\x80\x98\\0\xe2\x80\x99.\n\n The strrchr() function is identical to strchr() except it locates the\n last occurrence of c.\n*/\n\nchar* string = strdup ("THIS IS, A STRING WITH, COMMAS!");\n\nchar* ch = strrchr( string, ',' );\n*ch = 0;\n\nfree( string );\n\n/*\n The resulting string should be: "THIS IS, A STRING WITH"\n When the string pointer is freed, does this result in a memory leak?\n*/\nRun Code Online (Sandbox Code Playgroud)\n
我认为这不是一个愚蠢的问题。TLDR:不,你不会导致内存泄漏。
现在更长的答案:free不知道字符串是什么。如果你向它传递一个 char* 或一个 int* 它就不会在意。
malloc 和 free 的工作方式如下:当您调用 malloc 时,您提供一个大小并接收一个指针,并承诺从指针的位置开始在堆上保留许多字节。然而,此时大小和位置也会以某种方式在内部保存(这取决于并且是实现细节)。现在,当您调用 free 时,它不需要知道大小,它只需删除指针所属的条目以及大小即可
附录:也不是每个 char* 都指向一个字符串,恰巧“abcd”成为指向 的以空结尾的 char* 'a',但 char* 本身指向单个字符,而不是多个