c freeing char pointer not working after first time

192 views Asked by At

I am trying to free a char pointer wich was allocated by the function copyCharNumber. The first time the free call in the function works fine. The second time it doesn´t work any more and Visual Studio throws an error. I don`t get it why there is an error the second time. The second time calling free on the char pointer returned by the copyCharNumber anywhere in the code allways throws an error.

Code:

char* copyCharNumber(char *oldNumber, char *newDigit, int newLen){
    char* newNumber = malloc(newLen * sizeof(char) +1);
    if (oldNumber != NULL){
        strcpy(newNumber, oldNumber);
        free(oldNumber);
    }
    *(newNumber + (newLen - 1)) = *newDigit;
    *(newNumber + newLen) = "\0";
    return newNumber;
}

double* getNumbers(int max, int maxValue, int minValue, char* filenameRead){
    double* numbers = malloc(max * sizeof(double));
    FILE* fp = fopen(filenameRead, "r");
    char ch = NULL;
    int i = 0;
    int numberLen = 0;
    boolean isNegative = 0;
    int hasPoint = 0;
    for (; i < max && fp != NULL && ch != EOF; i++){
        isNegative = 0;
        numberLen = 0;
        hasPoint = 0;
        char* number = NULL;

        if (ch == NULL)
            ch = fgetc(fp);

        if (ch == '-') isNegative = 1;
        if (ch == '.' || ch == ',' && numberLen > 0) hasPoint++;

        while (isdigit(ch)>0 || (isNegative && numberLen == 0) || (hasPoint == 1 && numberLen>0)){
            numberLen++;
            number = copyCharNumber(number, &ch, numberLen);
            ch = fgetc(fp);
        }

        if (number != NULL){
            double newNumber = strtod(number, NULL);
            free(number);
            if (newNumber <= maxValue && newNumber >= minValue){
                if (isNegative) newNumber = -newNumber;
                numbers[i] = newNumber;
            }

        }
        else
            ch = NULL;
    }
    return numbers;
}
0

There are 0 answers