在结构中重新分配内存后出现奇怪的文本

时间:2019-05-06 09:13:13

标签: c

将字符串从指针打印到指针数组后,出现奇怪的字符。有时甚至崩溃,就像内存用完了一样。这是为什么? 每件事都必须是动态的。有时候,如果我只写一个或两个原因这些错误不会发生的原因。输出-a═══asda或adsas═²²²²²²════⌡X机架▒2。

#define MAX_LENGTH 50
#define ONE 1
#define TWO 2
#define THREE 3
#define EXIT 4

typedef struct list
{
    char** reasons;

}list;

int main(void)
{
    list pros = { (char*)malloc(sizeof(char) * MAX_LENGTH) };
    list cons = { (char*)malloc(sizeof(char) * MAX_LENGTH) };
    char* reason = 0;
    char* dillema  = 0;
    reason = (char*)malloc(sizeof(char) * MAX_LENGTH);
    dillema = (char*)malloc(sizeof(char) * MAX_LENGTH);
    printf("What is your dillema? \n");
    fgets(dillema, MAX_LENGTH, stdin);
    dillema[strcspn(dillema, "\n")] = 0;
    dillema = (char*)realloc(dillema, sizeof(char) * strlen(dillema) + ONE);

        switch (selection)
        {
        case ONE:
            printf("Enter a reason to add to list PRO: \n");
            fgets(reason, MAX_LENGTH, stdin);
            reason[strcspn(reason, "\n")] = 0;
            reason = (char*)realloc(reason, (sizeof(char) * strlen(reason)) + 1);
            pros.reasons = (char**)realloc(pros.reasons, (sizeof(char*) * prosCounter) + 1);
            strcpy(pros.reasons + prosCounter, reason);
            prosCounter += ONE;
            break;
        case TWO:
            printf("Enter a reason to add to list CON: \n");
            fgets(reason, MAX_LENGTH, stdin);
            reason[strcspn(reason, "\n")] = 0;
            reason = (char*)realloc(reason, (sizeof(char) * strlen(reason)) + 1);
            cons.reasons = (char**)realloc(cons.reasons, (sizeof(char*) * consCounter) + 1);
            strcpy(cons.reasons + consCounter, reason);
            consCounter += ONE;
            break;
        case THREE:
            printf("Your dillema: \n%s \n\n", dillema);
            printf("LIST PROS\n_________ \n");
            for (i = 0; i < prosCounter; i++)
            {
                printf("%s \n", pros.reasons + i);
            }
            printf("LIST CONS\n_________ \n");
            for (i = 0; i < consCounter; i++)
            {
                printf("%s \n", cons.reasons + i);
            }
            printf("\n\n");
            break;
        case EXIT:
            break;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

以下是导致问题的行(仅第二行,但我也显示了第一行来显示上下文):

pros.reasons = (char**)realloc(pros.reasons, (sizeof(char*) * prosCounter) + 1);
strcpy(pros.reasons + prosCounter, reason);

基本上,您是将整个字符串复制到未初始化的指针中。

如果只想指向该字符串,请为其分配一个指针。如果要复制,则应使用strndup()