简体   繁体   English

将字符串 char 设置为 null 是否会导致 C 中的 memory 泄漏?

[英]Does setting a string char to null cause a memory leak in C?

This seems like a silly question, but I couldn't find the answer.这似乎是一个愚蠢的问题,但我找不到答案。

Anyways, if you set an arbitrary character to null in a string, then free the string, does that cause a memory leak?无论如何,如果您在字符串中将任意字符设置为 null,然后释放该字符串,这会导致 memory 泄漏吗?

I suppose my knowledge of how the free function works is limited.我想我对免费 function 如何工作的了解有限。

/*
     char *
     strchr(const char *s, int c);

     char *
     strrchr(const char *s, int c);

     The strchr() function locates the first occurrence of c (converted to a
     char) in the string pointed to by s.  The terminating null character is
     considered part of the string; therefore if c is ‘\0’, the functions
     locate the terminating ‘\0’.

     The strrchr() function is identical to strchr() except it locates the
     last occurrence of c.
*/

char* string = strdup ("THIS IS, A STRING WITH, COMMAS!");

char* ch = strrchr( string, ',' );
*ch = 0;

free( string );

/*
    The resulting string should be: "THIS IS, A STRING WITH"
    When the string pointer is freed, does this result in a memory leak?
*/

Not a stupid question in my opinion.在我看来,这不是一个愚蠢的问题。 TLDR: no you do not cause a memory leak. TLDR:不,您不会导致 memory 泄漏。

Now the longer answer: free has no idea what a string is.现在更长的答案: free不知道字符串是什么。 If you pass it a char* or an int* it could not care less.如果您将其传递给 char* 或 int* ,它就不会在意。

The way malloc and free works is the following: when you call malloc you supply a size and receive a pointer with the promise of that many bytes being reserved on the heap from the position of the pointer onwards. The way malloc and free works is the following: when you call malloc you supply a size and receive a pointer with the promise of that many bytes being reserved on the heap from the position of the pointer onwards. However at that point the size and position are also saved internally in some way (this depends and is an implementation detail).然而,此时尺寸和 position 也以某种方式在内部保存(这取决于实现细节)。 Now when you call free it does not need to know the size, it can just remove the entry your pointer belongs to together with the size现在,当您调用 free 时,它不需要知道大小,它只需删除指针所属的条目以及大小即可

Addendum: also not every char* points to a string, it just so happens that "abcd" becomes a null terminated char* pointing to the 'a' , but a char* itself points to a single char, not multiple附录:也不是每个 char* 都指向一个字符串,碰巧 "abcd" 变成了 null 终止的 char* 指向'a' ,但是 char* 本身指向单个 char,而不是多个

malloc only allocates the chunk of memory and gives you the reference to it. malloc只分配 memory 的 chunk 并给你参考。 If you do not read or write outside the boundaries of this chunk you can do whatever you want with it.如果你不在这个块的边界之外读或写,你可以用它做任何你想做的事情。

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

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