-2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

typedef struct dictionary_entry
{
    char *eng;
    char *gr;
} term;

len = 0;
term *terms, *trm;
terms = (term*)malloc(0);
char temp1[50], temp2[50];
trm = (term*)malloc(0);
trm->eng = (char*)malloc(0);
trm->gr = (char*)malloc(0);
FILE *in = fopen("dictionary.txt", "r");
while(feof(in) == 0)
{
    fscanf(in, "%s %s\n", temp1, temp2);
    trm = (term*)realloc(trm, sizeof(term));
    trm->gr = (char*)realloc(trm, sizeof(char) * strlen(temp1));
    trm->eng = (char*)realloc(trm, sizeof(char) * strlen(temp2));
    strcpy(trm->gr, temp1);
    strcpy(trm->eng, temp2);
    add(&terms, trm, &len);
}
free(trm->eng);
free(trm->gr);
free(trm);
fclose(in);

I was trying to read sets of words from my file (eg. word translation) to create a dictionary but as soon as I run the program it crashes. The debugger points me out to the realloc function and an arror message appears. The message is

[debug]Cannot find bounds of current function

and the problem seems to have something to do with the realloc function I'm using. Has anyone faced that problem and if so how can I solve it?

I am using Code::Blocks.

  • 2
    Check the return value of `malloc`, `realloc`, `fopen` and `fscanf`, every time - always! And please read [this about `feof`](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Weather Vane Jan 19 '16 at 16:00
  • Harris, AgapwIesu this is just part of the program I just forgot to include the main() function here. The only problem is with the realloc() function – Johnny Tse Jan 19 '16 at 16:04

1 Answers1

1

You are not reallocating the correct struct fields with this

trm->gr = (char*)realloc(trm, sizeof(char) * strlen(temp1));
trm->eng = (char*)realloc(trm, sizeof(char) * strlen(temp2));

I suggest it should be

trm->gr = (char*)realloc(trm->gr, sizeof(char) * strlen(temp1));
trm->eng = (char*)realloc(trm->eng, sizeof(char) * strlen(temp2));

I notice you are using strlen to resize, so you perhaps need +1 for a string terminator too, which (also simplifying) would be

trm->gr = realloc(trm->gr, strlen(temp1) + 1);
trm->eng = realloc(trm->eng, strlen(temp2) + 1);

But you should always check the return values from functions too.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • I corrected it but there is still the same error appearing when I try to debug. – Johnny Tse Jan 19 '16 at 21:11
  • *"The only problem is with the realloc() function"* don't you believe it. If you don't know what is causing the error, you don't know what is relevant. That's why it is recommended to post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – Weather Vane Jan 19 '16 at 21:15