kjakeb
kjakeb

Reputation: 7600

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

Upvotes: 0

Views: 112

Answers (3)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 0

Igor Popov
Igor Popov

Reputation: 2620

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

Upvotes: 4

nio
nio

Reputation: 5289

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.

Upvotes: 3

Related Questions