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] = '[==]';

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

    return out;
}

char* drawLabel(char* label, int n)
{
    if (strlen(label) > n)
    {
        char* newLabel = (char*)malloc(sizeof(char)*(n+1));
        newLabel[0] = '[==]';
        strncpy(newLabel, label, n);
        newLabel[n] = '[==]';
        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] = '[==]';
    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);
}

谢谢你帮我解决这个问题。

你必须初始化input或像这样将其声明为数组

char input[16];

此外,您应该注意到 scanf 没有 return EOF 它 return 匹配的参数数量,因此您必须更改

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

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

因为 while(scanf("%15s", input) != EOF 总是正确的。

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

分配内存给input你还没有初始化你的指针。

指针应该指向某个有效的内存位置以通过 scanf()

存储值