简体   繁体   中英

Memory Leak in Returning a Pointer and Freeing it in C

I have the following code:

char *get_packet(int cc, char *args[]){

    char *packet;
    packet = (char*) malloc(30 * sizeof(char));

    //other code..

    ...

    return packet;
}

int main(){

    int cc = SCANS_TO_ACCUMULATE;
    int args[] = {5000};

    char *str_args[15];
    int i = 0;
    for(i; i<((sizeof(args)/sizeof(args[0]))); i++){
           char buffer[10];
           sprintf(buffer, "%d", args[i]);
           str_args[i] = strdup(buffer);
           free(buffer);
    }
    str_args[i] = NULL;

    char *pkt;
    pkt = get_packet(cc, str_args);
    printf("%s\n", pkt);
    free(pkt);
    pkt = NULL;
    getchar();

    return 0; 
}

However, running this causes my program to crash immediately, and after doing some inspection with Dr. Memory it appears I have a memory leak, but I can't seem to find why it's occurring. Am I not freeing the malloc'd memory correctly? Thanks in advance

Your code tries to deallocate memory of buffer which is not dynamically allocated,ie which is a local variable-array. This causes the crash.

Here:

char buffer[10];
...
free(buffer);

You cannot free local array, remove the call to the free . The memory will be freed up automatically when the variable gets out of scope.

Freeing the local array "buffer" is undefined, and probably horrible, behavior! You can't free something unless it was allocated with malloc() or calloc(). It's likely corrupting the heap and causing the crash.

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