1

When I try to call free() function to free the memory, it isn't working properly. Here is my code:

unsigned char *indata;
unsigned char *outdata;

int file_func(const char *filename) {
//some other variables

for(i=0;i < no_of_files;i++) {
indata = malloc(sizeof(unsigned char));
outdata = malloc(sizeof(unsigned char));

//counts the number of characters from filename
numCharacters = readfile(filename, indata); 

/* perform some operation on indata and get outdata(size is same as indata)*/

writefile(filename, outdata);   //writes outdata to filename

    free(indata);
    free(outdata);
    }
}

The above code does not work properly because free() is storing some random garbage value at indata & outdata(as they become dangling pointers). So I tried setting the pointers to null after freeing since I'm reusing the same pointers as:

    free(indata);
    indata = NULL;
    free(outdata);
    outdata = NULL;

Even then my code gets crashed as :

double free or corruption (out): 0x00000000025aa240 *

How can I overcome this problem or is there any other alternative to use dynamic sized pointers in a loop. Thank you.

4

1 回答 1

0

您只sizeof(unsigned char)为这些变量中的每一个分配 1 个字节 ( )。要么这是一个错误,你想分配sizeof(unsigned char) * some_number哪里some_number是动态的,或者你可以只在堆栈上分配:

unsigned char indata, outdata; // then use &indata and &outdata where you need a pointer

或者

unsigned char indata[some_number];
unsigned char outdata[some_number];

或者您可以在循环之前 malloc 一次,然后在循环之后释放一次。

双重免费问题看起来像您在循环中调用的函数之一正在调用免费。仔细查看 readfile 和 writefile。

于 2013-09-23T17:25:23.877 回答