簡體   English   中英

C程序崩潰

[英]C program crashes

嗨,我需要一些調試程序的幫助:它應該從控制台讀取,處理輸入並將其返回:

第二次調用while(scanf("%15s", input) != EOF)之后發生錯誤。 不幸的是,我無法告訴您錯誤是什么,因為程序凍結了,並且沒有提供任何信息。 我認為input var出了點問題(它被多次傳遞了)

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

char* repeat(char c, int n);
char* drawLabel(char* label, int n);
char* drawBarnorm(char* label, int value);
char* drawBar(char* label, double value);

int main(void)
{
    char* input;
    double numIn;
    char buf[] = "";
    char* pOutput = &buf[0];

    while(scanf("%15s", input) != EOF)
    {
        scanf("%lf", &numIn);
        if (numIn > 1)
        {
            if (numIn > 30)
            {
                printf("num to big!\n");
                return 0;
            }

            strcat(pOutput, drawBarnorm(input, (int)numIn));
        } else
            {strcat(pOutput, drawBar(input, numIn));}


        printf("%s\n", pOutput);
    }

    printf("%s\n", pOutput);
    return 0;
}

char* repeat(char c, int n)
{
    char* out = (char*)malloc(sizeof(char)*50);
    int i, len;
    out[0] = '\0';

    for (i = 0; i < n; ++i)
    {
        len = strlen(out);
        out[len] = c;
        out[len+1] = '\0';
    }

    return out;
}

char* drawLabel(char* label, int n)
{
    if (strlen(label) > n)
    {
        char* newLabel = (char*)malloc(sizeof(char)*(n+1));
        newLabel[0] = '\0';
        strncpy(newLabel, label, n);
        newLabel[n] = '\0';
        return newLabel;
    } else if (strlen(label) < n)
    {
        strcat(label, repeat(' ', n-strlen(label)));
    }

    return label;
}

char* drawBarnorm(char* label, int value)
{
    char* bar = (char*)malloc(sizeof(char)*41);
    char* barPart;
    bar[0] = '\0';
    bar = drawLabel(label, 8);
    strcat(bar, "|");
    barPart = drawLabel(repeat('#', value), 30);
    strcat(bar, barPart);
    strcat(bar, "|");
    return bar;
}

char* drawBar(char* label, double value)
{
    int val = (int)(30.0*value);
    return drawBarnorm(label, val);
}

謝謝您的幫助。

char* input = malloc(size); /* Allocate memory of your wish */

分配內存以input您尚未初始化指針。

指針應指向某個有效的內存位置以通過scanf()存儲值

您必須像這樣初始化input或將其聲明為數組

char input[16];

另外,您應該注意到scanf不會返回EOF它會返回匹配的參數數量,因此您必須進行更改

while(scanf("%15s", input) != EOF)

while(scanf("%15s", input) == 1)

因為while(scanf("%15s", input) != EOF始終為true。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM