在C中释放字符串 [英] Freeing strings in C

查看:181
本文介绍了在C中释放字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要写:

char *a=malloc(sizeof(char)*4);
a="abc";
char *b="abc";

我需要释放此内存,还是由系统完成?

do I need to free this memory, or is it done by my system?

推荐答案

在您的情况下,您将无法释放动态分配的内存,因为您将丢失对它的引用.

In your situation you won't have any way to free the dynamic allocated memory because you are losing the reference to it.

尝试一下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *a=(char*)malloc(sizeof(char)*4);
  printf("Before: %p\n",a);
  a = "abc";
  printf("After: %p\n",a);
  free(a);
  char *b = "abc";

  return 0;
}

您将获得

Before: 0x100100080
After: 0x100000f50

您将看到两个指针是不同的.这是因为字符串文字"abc"被放置在二进制文件的数据扇区中,并且在您这样做的时候

You will see that the two pointers are different. This because the string literal "abc" is placed into data sector of the binary files and when you do

a = "abc"

您正在更改a的指针以指向常量文字字符串"abc",并且您正在丢失先前分配的内存.在a上调用free不再正确,只是因为它不再指向有效的动态分配地址.为了保留指针并能够释放它,您应该使用

you are changing the pointer of a to point to the constant literal string "abc" and you are losing the previously allocated memory. Calling free on a is not correct anymore, just because it won't point to a valid dynamically allocated address anymore. To preserve the pointer and be able to free it you should copy the string with

strncpy(a, "abc", 4)

这将有效地将字符从立即数复制到动态分配的方法,同时保留原始指针.

This will effectively copy characters from the literal to the dynamically allocated method, preserving the original pointer.

这篇关于在C中释放字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆