简体   繁体   中英

Segmentation fault while mallocing 2d arrays?

I am getting a segmentation fault on line 57 and am not sure why...:

41    int numRows = C/(K*L);
42    int numCols = K;
43  
44    tagArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
45    lruArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
46  
47    for(int i = 0; i<numRows;i++)
48      {
49        *(tagArray + i) = (int*) malloc(numCols*sizeof(int)); // fills each row with K columns
50        *(lruArray + i) = (int*) malloc(numCols*sizeof(int)); // fills each row with K columns
51      }
52  
53    for(int i = 0; i<numRows; i++)
54      for(int j = 0; j<numCols; j++)
55        {
56          tagArray[i][j] = -1;
57          lruArray[i][j] = -1;
58        }
59  

Is there something that i'm missing? I'm pretty confident that I am mallocing correctly..

In

 tagArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows lruArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows 

you have to allocate space for an int* not an int .

Do not cast the result of malloc() in C!

44    tagArray = malloc(numRows*sizeof(int *));
45    lruArray = malloc(numRows*sizeof(int *));
46  
47    for(int i = 0; i<numRows;i++)
48      {
49        tagArray[i] = malloc(numCols*sizeof(int));
50        lruArray[i] = malloc(numCols*sizeof(int));
51      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM