0

Im writing this program for a class assignment in C. Its to simulate reading and writing to a custom-sized direct-mapped cache, involving a custom-sized main memory.

These are the parameters I used before getting Segmentation fault:

Enter main memory size (words):  65536
Enter cache size (words):  1024
Enter block size (words/block):  16

This is my code. Its not complete yet.

#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 */
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
azizoh
  • 97
  • 1
  • 1
  • 2
  • 1
    could you please format the code nicely as a first step (e.g. eliminate all the blank lines, indent it properly, ...) so it's not a huge hassle to read it? thanks. –  Oct 10 '15 at 09:10

1 Answers1

5

Three issues:

  1. These

    struct main *mainptr=(struct main *)malloc(cacheSize);
    struct main *mainnxt=(struct main *)malloc(cacheSize);
    

    needs to be

    struct main *mainptr = malloc(cacheSize * sizeof *mainptr);
    struct main *mainnxt = malloc(cacheSize * sizeof *mainnxt);
    

    because

    1. Casting the result of malloc (and family) is not required in C
    2. You should supply the number of bytes for allocating to malloc and not just the amount of struct main you want to allocate.
  2. You need to allocate memory for mainHd before using it here:

    mainHd->next=mainptr;
    

    Something like

    mainHd = malloc(sizeof *mainHd); 
    

    will do the trick!

  3. Don't forget to free the allocated memory after its use.

Side note: Check the result of malloc to see if it was successful.

Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83