c - 使用 char * 和 malloc 数组的 C 程序中的段错误

标签 c pointers segmentation-fault malloc

愚蠢的小 C 程序,但对于我的生活,我无法弄清楚为什么我总是遇到段错误。我相信我正在使用 malloc 分配足够的内存。任何帮助将非常感激。该代码应该从用户那里读取一个月中的某一天和“提醒”字符串,然后将这些读取到数组提醒指向的数据中,并使用 malloc 分配内存空间。

/* Prints a one-month reminder list (dynamic string version) */

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

#define MAX_REMIND 50           /* maximum number of reminders */
#define MSG_LEN 60              /* maximum length of reminder message */

int read_line(char str[], int n);

int main(void)
{
    char *reminders[MAX_REMIND];
    char day_str[3], msg_str[MSG_LEN+1];
    int day, i, j, num_remind = 0;

    for (;;) {
        if (num_remind == MAX_REMIND) {
            printf("-- no space left --\n");
            break;
        }

        printf("Enter day and reminder: ");
        scanf("%2d", &day);
        if (day == 0) {
            break;
        } 
        sprintf(day_str, "%2d", day);
        read_line(msg_str, MSG_LEN);

        for (i = 0; i < num_remind; i++) {
            if (strcmp(day_str, reminders[i]) < 0) {
                break;
            }
        }
        for (j = num_remind; j > i; j--) {
            reminders[j] = reminders[j-1];
        }

        reminders[i] = malloc(2 + strlen(msg_str) + 10);
        if (reminders[i] = NULL) {
            printf("-- No Space Left --\n");
            break;
        }

        strcpy(reminders[i], day_str);
        strcat(reminders[i], msg_str);

        num_remind++;
    }

    printf("\nDay Reminder\n");
    for (i = 0; i < num_remind; i++) {
        printf(" %s\n", reminders[i]);
    }

    return 0;
}
int read_line(char str[], int n) {
    int ch, i = 0;

    while ((ch = getchar()) != '\n') {
        if (i < n) {
            str[i++] = ch;
        }
    }
    str[i] = '\0';
    return i;
}

最佳答案

    if (reminders[i] = NULL) {

在取消引用之前将 reminders[i] 设置为 NULL

关于c - 使用 char * 和 malloc 数组的 C 程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8516511/

相关文章:

java - C 整数与 Java 读取的字节并集并重新转换为 Java int

c - 原型(prototype) "const int* foo(int)"是什么意思,特别是与 "int* foo(int)"相比?我只理解第二个

c++ - 可以在地址 0 分配一个有效的指针吗?

windows - 在 Windows 上的内存区域上设置 PAGE_NOACCESS 和 VirtualLock

c - 将值从 R 传递到 C 后,接收 *** 捕获段错误 ***、 'memory not mapped' 和损坏的结果

c++ - 如何在 c/c++ 的命令行程序中创建 --help 选项?

c - 如何释放分配的内存?

c - 普通链表中的队列

c++ - 遍历指针 vector

java - 什么会导致 Java native 函数(在 C 中)在进入时出现段错误?