c释放char指针在第一次之后不工作

时间:2015-06-18 09:10:54

标签: c pointers malloc free

我正在尝试释放由函数copyCharNumber分配的char指针。第一次在函数中的免费调用工作正常。第二次它不再工作,Visual Studio抛出错误。我不明白第二次出现错误的原因。第二次在代码中的任何地方copyCharNumber返回的char指针上调用free会抛出错误。

代码:

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 个答案:

没有答案