valentin.ciprian
valentin.ciprian

Reputation: 91

How do i deallocate memory here? (c)

I have a really quick question. Why do i get heap corruption detected when i try to deallocate the array in the void translateWord() function? I tried to deallocate line by line in a for loop but it doesnt seem to work. I thought that if i use that function more than once, and every time the function allocates memory, i should deallocate it at the end of the function. Any idea?

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>


void translateWord(char word[], FILE *point_out, FILE *point_1)
{
    rewind(point_1);
    char ch;
    int gasit = 0;
    int lines = count_lines(point_1);
    int i = 0;
    char *cp;
    char *bp;
    char line[255];
    char **array = (char**)malloc(sizeof(char*)*2*lines);

    rewind(point_1);
    while (fgets(line, sizeof(line), point_1) != NULL) {
        bp = line;
        while (1) {
            cp = strtok(bp, "=\n");
            bp = NULL;

            if (cp == NULL)
                break;
            array[i] = (char*)malloc(sizeof(char)*strlen(cp));
            strcpy(array[i++], cp);
        }
    }

    gasit = cuvant_gasit(word, array, lines, point_out, gasit);
    if (gasit == 0)
    {
        fprintf(point_out, "<<%s>>", word);
    }

    for (int k = 0; k < 2 * lines; k++)
    {
        free(array[k]);
    }
    free(array);
}

Upvotes: 0

Views: 108

Answers (1)

bruno
bruno

Reputation: 32596

There is something wrong in translateWord :

array[i] = (char*)malloc(sizeof(char)*strlen(cp));
strcpy(array[i++], cp);

The first line must be array[i] = (char*)malloc(strlen(cp) + 1); else 1 char is missing to save the final null char during the strcpy.

Note that by definition sizeof(char) is 1.

And why do you not just use strdup rather than a malloc then a strcpy ? just replace these 2 lines by array[i++] = strdup(cp);

Upvotes: 3

Related Questions