释放的malloc不会删除char数据 [英] Freeing malloc will not erase char data

查看:119
本文介绍了释放的malloc不会删除char数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了我更大的问题的一个较小的场景。我尝试做的是传递一个字符串的函数,这将使一个新的字符串出来。不过,我遇到了一些问题。

我已经定义字符串

 的typedef字符字符串[1024];

然后,我有一个函数,将一个字符串使得它得到填补与旧的字符串和字符点阵一个新的字符串

 字符串* add_sth_to_string(字符* MSG){
    字符串* =中newstr的malloc(sizeof的(字符串)); // malloc的一个中newstr
    的strcpy(*中newstr,味精); //复制味精中newstr    字符的buff [1024]; //做一个缓冲
    strcat的(BUFF,); //增加一个点的缓冲
    strcat的(BUFF,*中newstr); //加入味精缓冲
    的strcpy(*中newstr,浅黄色); //复制到缓冲区中newstr
    返回中newstr;
}

然后在主我试着每次使用这个功能3次,一个新的字符串:

 为(i = 0;我3;;我++){
    *字符串中newstr;
    =中newstr add_sth_to_string(测试);
    的printf(STR:%S \\ n,*中newstr);
    免费(中newstr);
    //甚至可以在这里的printf
}

这是怪异的输出获得:

  STR:.TEST
STR:.test.test
STR:.test.test.test

当我希望得到:

  STR:.TEST
STR:.TEST
STR:.TEST

任何人谁可以指出发生了什么事?别的东西我觉得奇怪的是,我可以的printf的中newstr的价值就在我拥有的释放


解决方案

您正在使用 BUFF 没有初始化它。尝试:

 字符的buff [1024];
抛光轮[0] = 0;


  

别的东西,我觉得奇怪的是,我可以的printf的中newstr价值
  就在我已经释放了。


释放后访问内存的未定义行为即可。通常情况下,出于性能的考虑,免费不为零的内存。

这是2案件未定义行为在同样的问题加一个很奇怪的的typedef 。继续努力吧!

I made a smaller scenario of my bigger problem. What I try to do is pass a string to a function which will make a new string out of it. However I ran into some problems.

I have defined string as

typedef char string[1024];

Then I have a function that takes a string and makes a new string which get filled with the old string and a dot char

string* add_sth_to_string(char* msg){
    string* newStr=malloc(sizeof(string)); // malloc a newStr
    strcpy(*newStr, msg);            // copying msg to newStr

    char buff[1024];                 // making a buffer
    strcat(buff, ".");               // adding a dot to buffer
    strcat(buff, *newStr);           // adding msg   to buffer
    strcpy(*newStr, buff);           // copying buffer to newStr
    return newStr;
}

Then in main I try to use this function 3 times for a new string each time:

for (i=0; i<3; i++){
    string* newStr;
    newStr=add_sth_to_string("test");
    printf("str: %s\n", *newStr);
    free(newStr);
    // can even printf here
}

This is the weird output I get:

str: .test
str: .test.test
str: .test.test.test

When I would expect to get:

str: .test
str: .test
str: .test

Anyone who can point out what is happening? Something else I find weird is that I can printf the value of newStr just after I have freed it.

解决方案

You are using buff without initializing it. Try:

char buff[1024];
buff[0] = 0;

Something else I find weird is that I can printf the value of newStr just after I have freed it.

Accessing memory after freeing it is undefined behavior. Typically, for performance reasons, free doesn't zero the memory.

That's 2 cases of undefined behavior in the same question + one really weird typedef. Keep it up!

这篇关于释放的malloc不会删除char数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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