-1

I need to create dynamic array of Parents where lastname is dynamic. But I receive an error about error reading characters of string.

parent ** getParents(){
    parent parent_in;
    parent** parentsArray=NULL;
    char answer;
    int i, numOfParents=0,fExit=0;

    do
    {
        printf("Do you wan't to enter parent? Y/N\n");
        flushall();
        scanf("%c", &answer);
        if (answer == 'N')
        {
            fExit = 1;
        }
        else
        {

            parent_in.lastname = (char*)malloc(20 * sizeof(char));

            parentsArray = (parent**)realloc(parentsArray, 1 * sizeof(parent*));
            parentsArray[numOfParents] = (parent*)calloc(1, sizeof(parent));

            printf("Please enter the lastname and num of childrens\n");
            scanf("%s %d", &parentsArray[numOfParents]->lastname, &parentsArray[numOfParents]->numOfChildren);

            numOfParents++;
            free(parent_in.lastname);
        }
    } while (fExit == 0);

    return parentsArray;
}

Here is struct of parents:

struct Parents{
    char *lastname;
    int numOfChildren;
}typedef parent;
gabeio
  • 1,282
  • 1
  • 23
  • 37

1 Answers1

1

Your code is a bit wired, as you mix the use of data structure parent_in with the use of parentsArray and it's entries; you malloc on the one, and use it at the other (e.g. concerning parent_in).

But concerning your error, there are two main issues that I see immediately:

  1. You scanf a string into a non-initialized pointer, i.e scanf("%s %d", &parentsArray[numOfParents]->lastname, .... Note that you might have reserved space for a parents structure; this structure has a pointer to lastname, which for itself does not get "malloced".

  2. You (re)-allocate always to the same number of entries, i.e. 1 in parentsArray = (parent**)realloc(parentsArray, 1 * sizeof(parent*)). You probably meant realloc(parentsArray, (numOfParents+1) * sizeof(parent*)).

I suppose that point 1 is responsible for your "error reading characters of string"; If you overcome this, I'm rather sure that point 2 will lead to the next memory corruption.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58