简体   繁体   中英

attempt to free memory causes error

I have declared the following struct:

typedef struct _RECOGNITIONRESULT {
        int begin_time_ms, end_time_ms;
        char* word;
} RECOGNITIONRESULT;

There is a method that creates an array of RECOGNITIONRESULT and fills it (for test purposes only):

void test_realloc(RECOGNITIONRESULT** p, int count){
    int i;
    *p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));
    for (i = 0; i < count; i++){
        (*p)[i].begin_time_ms = 2*i;
        (*p)[i].end_time_ms = 2*i+1;
        (*p)[i].word=(char *) malloc ( (strlen("hello"+1) * sizeof(char ) ));
        strcpy((*p)[i].word,"hello");
    }
}

The method to free memory is:

void free_realloc(RECOGNITIONRESULT* p, int count){
    int i = 0;
    if(p != NULL){
        if (count > 0){
            for (i = 0; i < count; i++){
                free(p[i].word);      //THE PROBLEM IS HERE.
            }
        }
        free(p);
    }
}

The main method calls those methods like this:

int main(int argc, char** argv)
{
    int count = 10;
    RECOGNITIONRESULT *p = NULL;
    test_realloc(&p,count);
    free_realloc(p,count);
    return 0;
}

Then if I try to free the memory allocated for "word", I get the following error:

HEAP CORRUPTION DETECTED: after normal block (#63) at 0x003D31D8. CRT detected that the application wrote to memory after end of heap buffer.

Using the debugger I've discovered that the crash occurs when calling free(p[i].word);

What am I doing wrong? How can I free he memory for the strings?

The problem is in your allocation of memory for word . strlen("hello"+1) should be strlen("hello")+1 .

Since you appear to allocate a whole array of structures in one strike

RECOGNITIONRESULT **p;
*p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));

you can free them in one call to free() as well :

void free_realloc(RECOGNITIONRESULT *p, int count){
        free(p);
}

And the strlen("hello"+1) is also wrong, as detected by Chowlett.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM