Question

This is my code:

int load_data(char *line, int *vertex, int *edge)
{
    char *ch_number = NULL;
    char *error = NULL;

    *vertex = (int)strtol(line, &error ,10);
    if((error[0] != '-') && (error[1] != '>')) return 0;

    ch_number = (char*)malloc(sizeof(char) * (strlen(error) - 2));

    memcpy(ch_number, &error[2], strlen(error) - 2);
    ch_number[strlen(error) - 2] ='\0';

    *edge = (int)strtol(ch_number, &error ,10);

    if(error[0] != '\0') 
    {
        free(ch_number);
        return 0;   
    }
    free(ch_number);
    return 1;
}

Debugger shows that free(ch_number); makes heap corruption. What am i doing wrong? This is the example of using:

load_data("15643->45545546",&vertex,&edge);

Was it helpful?

Solution

C arrays are zero based so the line

 ch_number[strlen(error) - 2] ='\0';

writes one byte beyond the end of ch_number. The effects of doing this are undefined but it sounds like you've written to a guard word used by the heap manager to detect exactly this sort of corruption.

If you want to add a null terminator to ch_number, you need to allocate an extra byte of memory

ch_number = malloc(strlen(error) - 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top