仅在调试时更正输出

时间:2014-07-25 11:00:05

标签: c arrays pointers memory struct

我在C中完成家庭作业有些麻烦。 我遇到了一个奇怪的问题,当程序在使用调试器运行时给我预期的输出,但是当正常运行时我得到一个奇怪的结果。

该程序采用2个多项式并打印出2的和和乘积。 多项式的输入只是[系数] [幂] [系数] [幂]的形式等等。

正确打印总和。以下是使用的函数:

void printPolynome(MONOM* poly, int size)
 {
     int i;

     for (i=0; i<size; i++)
     {
         if ((poly[i].coefficient > 0)&&(i != 0))
             printf("+");

         if (poly[i].power == 0)
             printf("%d", poly[i].coefficient);
         else if (poly[i].power == 1)
         {
             printf("%dx", poly[i].coefficient);
         }
         else
            printf("%dx^%d", poly[i].coefficient, poly[i].power);
     }

     if (size == 0)
         printf("0");
 }

void printSumPolynomes(MONOM *p1, int s1, MONOM *p2, int s2)
 {
     int phSize = s1+s2;
     MONOM* res = (MONOM*) malloc(phSize * sizeof(MONOM)); // Worst case size of result polynome

     int i=0;
     int j=0;
     int resInd=0;
     int finalSize = 0;

     while ( (i<s1) && (j<s2) )
     {
         if (p1[i].power > p2[j].power)
         {
             res[resInd] = p1[i];
             i++;
         }
         else if (p1[i].power < p2[j].power)
         {
             res[resInd] = p2[j];
             j++;
         }
         // If numbers have the same power, sum the coefficients.
         else if (p1[i].power == p2[j].power)
         {
             if (p1[i].coefficient + p2[j].coefficient != 0)
             {
                 p1[i].coefficient += p2[j].coefficient;
                 res[resInd] = p1[i];
                 j++;
                 i++;
             }
             else
             {
                 j++;
                 i++;
                 resInd--;
                 finalSize--;
             }
         }

         resInd++;
         finalSize++;
     }
     // Take care of leftovers and add them to array.
     while (i < s1)
     {
         res[resInd] = p1[i];
         resInd++;
         i++;
         finalSize++;
     }
     while (j < s2)
     {
         res[resInd] = p2[j];
         resInd++;
         j++;
         finalSize++;
     }

     // Clip array if needed.
     if (phSize > finalSize)
        res = (MONOM*) realloc(res, finalSize * sizeof(MONOM));

     printPolynome(res, finalSize);
     free(res);
 }

void printMulPolynomes(MONOM *p1, int s1, MONOM *p2, int s2)
{
    int phSize = s1*s2;
    int i;
    int j;
    int resInd = 0;
    int mulSize = 0;

    MONOM* res = (MONOM*) malloc (phSize * sizeof(MONOM));

    for (i=0; i<s1; i++)
    {
        for (j=0; j<s2; j++)
        {
            res[resInd].coefficient = p1[i].coefficient * p2[j].coefficient;
            res[resInd].power = p1[i].power + p2[j].power;
            mulSize++;
            resInd++;
        }
    }

    // use sortInput function to sort the result.
    sortInput(res,mulSize);

    // calculate number of monoms in result
    i=0;
    mulSize = 0;
    while (res[i].power >= 0)
    {
        mulSize++;
        i++;
    }

    if (phSize > mulSize)
        res = (MONOM*) realloc(res, mulSize * sizeof(MONOM));

    printPolynome(res, mulSize);
    free(res);
}

这是getPolynome函数:

MONOM* getPolynome(int* logSize)
 {
    int phSize = INIT_SIZE; // physical size
    int initLogSize = 0; // logical size of initial input
    int ch;
    int i = 0;
    int j = 0;
    int countLegalMonoms = 0;
    int countNums = 0;
    char* marker;
    char* userInput;
    char* token;
    MONOM* poly;
    BOOL sumFlag;
    int currCoef, currPow; // Variables for current coefficient and power input

    // Get the first char of input
    ch = getchar();

    // Create array for raw user input
    userInput = (char*) malloc (phSize * sizeof(char));

    while (ch != EOL)
    {
        if (phSize == initLogSize)
        {
            phSize *= 2;
            userInput = (char*) realloc (userInput, phSize);

        }

        userInput[i] = ch;
        initLogSize++;
        i++;

        // get next input
        ch = getchar();
    }
    userInput[i] = EOS;

    // Check how many numbers are in the array.
    marker = userInput;
    while (*marker != EOS)
    {
        if ( (*marker == ' ') || (*marker != ' ')&&(*(marker+1) == '\0') )
            countNums++;

        marker++;
    }

    // Create monoms array - a polynome
    poly = (MONOM*) malloc (countNums/2 * sizeof(MONOM));

    // Take the first token
    token = strtok(userInput, " ");

    while (token != NULL)
    {
        sumFlag = FALSE;

        sscanf(token, "%d", &currCoef);
        token = strtok(NULL, " ");
        sscanf(token, "%d", &currPow);

        // Check if the current power exists.
        for (i=0; i < countNums/2; i++)
        {
            if (poly[i].power == currPow)
            {
                poly[i].coefficient += currCoef;
                sumFlag = TRUE;

                // Check if the coeeficient sums to 0
                if (poly[i].coefficient == 0)
                    poly[i].power = COEF_NULL_FLAG; // Will be used later to remove from array.
            }
        }

        // Summation was not performed. Creating a new monom.
        if (sumFlag == FALSE)
        {
            poly[j].power = currPow;
            poly[j].coefficient = currCoef;
            j++;
        }

        token = strtok(NULL, " ");
    }


    // We now want to sort the array.
    sortInput(poly, j);

    // Count how many legal monoms are currently in the array
    for (i=0; i < j; i++)
    {
        if (poly[i].power != COEF_NULL_FLAG)
            countLegalMonoms++;
    }

    // Finished dealing with data - clip the array
    poly = (MONOM*) realloc (poly, countLegalMonoms * sizeof(MONOM));

    *logSize = countLegalMonoms;
    return poly;
}

这是主要功能:

#define _CRT_SECURE_NO_WARNINGS
#define INIT_SIZE 2
#define EOL '\n'
#define EOS '\0'
#define COEF_NULL_FLAG -1
#define TRUE 1
#define FALSE 0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct monom{ 
    int coefficient; 
    int power; 
}MONOM;

typedef int BOOL;

...

void main() {
    int myLogSize1, myLogSize2;
    MONOM* myPoly1;
    MONOM* myPoly2;

    printf("Please enter first polynome:");
    myPoly1 = getPolynome(&myLogSize1);
    printf("Please enter second polynome:");
    myPoly2 = getPolynome(&myLogSize2);

    printf("\n");
    printf("The sum of polynomes is: ");
    printSumPolynomes(myPoly1, myLogSize1, myPoly2, myLogSize2);
    printf("\n");
    printf("The multiplication of polynomes is: ");
    printMulPolynomes(myPoly1, myLogSize1, myPoly2, myLogSize2);

    printf("\n");


    free(myPoly1);
    free(myPoly2);
}

这是我得到以下输入的输出:

Please enter first polynome:-2 2 2 3
Please enter second polynome:2 2

The sum of polynomes is: 2x^3
The multiplication of polynomes is: 4x^5-4x^4-33686019x^50865+5198872x^5177540+1
389377768x^201377471+5340200x^5349952+1428628924x^274+24x^2
Press any key to continue . . .

非常感谢您的帮助,我真的无法找到输出中所有额外垃圾的来源。

1 个答案:

答案 0 :(得分:1)

我认为问题在于void printSumPolynomes(MONOM * p1,int s1,MONOM * p2,int s2):

// calculate number of monoms in result
i=0;
mulSize = 0;
while (res[i].power >= 0)
{
    mulSize++;
    i++;
}

只有在遇到功率小于零时才会停止。因为你没有初始化你的数组res而只是

  

MONOM * res =(MONOM *)malloc(phSize * sizeof(MONOM));

它将扫描未分配的内存并导致垃圾输出。

AIUI你甚至不需要那些代码,因为你已经在mulSize

中拥有了你的最终尺寸

编辑: 实际上mulSize是s1 * s2,而这是你的多项式的最终大小,你可以考虑将术语与相应的权力结合起来,就像在getPolynome()中完成的那样

编辑: 未明确初始化res数组不会导致此问题,因为所有条目(2)实际上都将设置为正确的值,但计算monom数量的循环不会在数组的末尾终止。