免费()返回字符指针不会从内存中删除呢? [英] Free() returned char pointer doesn't remove it from memory?

查看:159
本文介绍了免费()返回字符指针不会从内存中删除呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上这个问题归结到这一点:

Basically the problem comes down to this:

我打开一个文件,写入所有的每个字符到一个char *变量,它具有的malloc()的文件的长度。然后我返回变量,并打印出来,那么我释放()该变量的内存并尝试再次打印变量,并打印出来。

I load a file, write all the each character into a char* variable which has malloc() the length of the file. Then I return that variable and print it, then I free() the memory for that variable and try to print the variable again which does print it.

我很新的C所以有可能出错了我在处理用于保存文本内容的变量内存的方式。

I'm very new to C so there is probably something wrong in the way I handle the memory for the variable that holds the text content.

我尝试使用替代的malloc和char *的char [(FTELL(文件),但随后的函数没有返回任何东西。这可能是因为它是当函数不会返回它被释放一个局部变量,对不对?

I tried using char[(ftell(file)] instead of malloc and char*, but then the function didn't return anything. That's probably because it's a local variable which gets freed when the function does return, right?

下面是我的code样子:

Here's what my code looks like:

main.c中:

#include <stdio.h>
#include <stdlib.h>
#include "data/filesystem/files.h"

int main(){
    char *filebuffer = retrieve_file_content("assets/test.txt");
    printf("%s", filebuffer);
    free(filebuffer);
    printf("%s", filebuffer);
    return 0;
 }

files.c:

files.c:

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

char *retrieve_file_content(char* path){
    FILE *file;
    file = fopen(path, "r");
    if(file){
        fseek(file, 0L, SEEK_END);
        char *filebuffer = malloc(ftell(file));
        if(filebuffer == NULL){ return NULL; }
        fseek(file, 0L, SEEK_SET);
        int i = 0;
        int buffer = getc(file);
        while(buffer != EOF){
            filebuffer[i] = buffer;
            buffer = getc(file);
            i++;
        }
        fclose(file);
        return filebuffer;
    }else{
        return NULL;
    }
}

test.txt的:

test.txt:

heheasdasdas

输出:

heheasdasdas
heheasdasdas

在此先感谢!

推荐答案

免费只是标志着有问题的内存是免费的再次分配,这意味着它可以重复使用。但它不设置释放的内存为任意值。你的榜样就是所谓UB(未定义行为)。有未定义行为的程序可能在技术上做任何事情 - 包括错误/奇怪的行为,良好行为,或通过Skype订购比萨饼:)

free just marks that the memory in question is free to be allocated again, that means it can be reused. But it doesn't set the freed memory to any value. Your example is what is called UB (Undefined Behavior). Programs having Undefined Behavior may technically do anything - including wrong/strange behavior, good behavior, or ordering a pizza via skype :)

这篇关于免费()返回字符指针不会从内存中删除呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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