C:分段故障(核心转储)

azi*_*zoh 0 c segmentation-fault

我正在为C中的类赋值编写这个程序.它模拟读取和写入自定义大小的直接映射缓存,涉及自定义大小的主内存.

这些是我在获得之前使用的参数Segmentation fault:

Enter main memory size (words):  65536
Enter cache size (words):  1024
Enter block size (words/block):  16
Run Code Online (Sandbox Code Playgroud)

这是我的代码.它尚未完整.

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

struct cache{
     int tag;
     int *block;
};

struct main {
     int value;
     int address;
     int word;

     struct main *next;
};

struct cache   *cacheptr;
struct main    *mainHd;

int main() {
    int option = 0;

    while (option != 4) {
        printf("Main memory to Cache memory mapping:\n--------------------------------------");
        printf("\n1) Set parameters\n2) Read cache\n3) Write to cache\n4) Exit\n\nEnter Selection: ");
        scanf("%d",&option);
        printf("\n");

        if (option == 1) {
            int mainMemory, cacheSize, block;

            printf("Enter main memory size (words):  ");
            scanf("%d",&mainMemory);

            printf("Enter cache size (words):  ");
            scanf("%d",&cacheSize);

            printf("Enter block size (words/block):  ");
            scanf("%d",&block);

            struct main *mainptr=(struct main *)malloc(cacheSize);
            mainHd->next=mainptr;

            for (int i=1; i < mainMemory; i++) {
                mainptr->value=mainMemory-i;
                mainptr->address=i;
                mainptr->word=i;

                struct main *mainnxt=(struct main *)malloc(cacheSize);
                mainptr->next=mainnxt;
                mainptr=mainnxt;
            }
        } /* end if */
    } /* end while */
} /* end main */
Run Code Online (Sandbox Code Playgroud)

Spi*_*rix 5

三个问题:

  1. 这些

    struct main *mainptr=(struct main *)malloc(cacheSize);
    struct main *mainnxt=(struct main *)malloc(cacheSize);
    
    Run Code Online (Sandbox Code Playgroud)

    需要是

    struct main *mainptr = malloc(cacheSize * sizeof *mainptr);
    struct main *mainnxt = malloc(cacheSize * sizeof *mainnxt);
    
    Run Code Online (Sandbox Code Playgroud)

    因为

    1. mallocC中不需要转换(和族)的结果
    2. 您应该提供分配的字节数,malloc而不仅仅是struct main您要分配的数量.
  2. mainHd在此之前使用它需要分配内存:

    mainHd->next=mainptr;
    
    Run Code Online (Sandbox Code Playgroud)

    就像是

    mainHd = malloc(sizeof *mainHd); 
    
    Run Code Online (Sandbox Code Playgroud)

    会做的!

  3. 使用后不要忘记free分配的内存.

附注:检查结果malloc是否成功.