You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言中将字符串字符设为NULL会导致内存泄漏吗?

问题:修改字符串中的字符为NULL后释放是否会导致内存泄漏?

我遇到一个看似简单但找不到答案的问题:如果把字符串中的任意字符设为NULL(即'\0'),之后再释放这个字符串,会不会引发内存泄漏?我对free函数的工作原理了解有限,相关代码示例如下:

/*
     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?
*/
解答:不会产生内存泄漏

原因和free的工作逻辑直接相关:

  • strdup函数会为原完整字符串(包括末尾的终止'\0')分配足够的内存空间,然后把原字符串的所有内容复制进去,返回的指针指向这个内存块的起始地址。内存管理系统会在内部记录这个指针对应的内存块总大小。
  • 你用strrchr找到最后一个逗号并将其改为'\0',只是改变了字符串的逻辑长度——从这个位置开始,后续字符不再被视为字符串的有效部分,但这完全不影响内存块的物理大小,也不会改变内存管理系统记录的块信息。
  • free函数的工作依据是你传入的指针(必须是malloc/calloc/realloc/strdup这类分配函数返回的起始指针),它会直接根据内部记录的该指针对应的内存块总大小,将整个块的内存全部释放回收,和字符串中'\0'的位置没有任何关系。

简单说:你分配了多少内存,free就会释放多少,不管你有没有修改过字符串内容。所以这段代码不会产生内存泄漏。

内容的提问来源于stack exchange,提问作者NorthStar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:27:37