Ted Jenkins
Ted Jenkins

Reputation: 15

Error when freeing calloc'd memory: free invalid next size (fast)

I'm writing a function to get text from a file and I'm encountering an issue when I try and free some calloc'd memory.

ye. wee.\n

when a txt file with the above is passed, the function allocates memory for the 3 char characters of ye. and copies them in. Then allocates memory for the other 6 characters and copies them in. Then it prints the respective strings and frees the memory.

testFor() is a function that returns the index of the first '.' in a string.

I've examined the program in gdb and when it hits free(key) it causes a segfault with the following error (sorry, can't embed images yet).

//more above    
while ((fgets(line, 256, source_fp)) != NULL) {
            if (line[0] == '\n') {
                if (pflag) {
                    int first = testFor(definition);
                    int second = strlen(definition);
                    printf("%d %d\n", first, second);
                    key = calloc(first + 1, sizeof(char));
                    defn = calloc((second - (first + 1)), sizeof(char));
                    for (i = 0; i < (first + 1); i++) {
                        key[i] = definition[i];
                        }
                    int x = i + 1;
                    for (; i < second; i++) {
                        defn[i-x] = definition[i];
                        }
                    printf(">%s<\n", key);
                    printf(">%s<\n", defn);
                    free(key);
                    free(defn);
                    }
                    //more

I'm still new to using the memory allocation so this has me confused.

Upvotes: 1

Views: 332

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223409

When defn[i-x] = definition[i]; is evaluated the first time, x has the value i+1, so i-x is -1.

Upvotes: 2

Related Questions