c - 具有动态内存分配的嵌套 for 循环中的段错误

标签 c for-loop nested nested-loops dynamic-memory-allocation

我正在准备使用 C 语言模拟距离 vector 路由的代码,但是,我在运行时遇到了段错误。 代码:-

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

/* Date : 03/06/2018
 *
 * Algorithm
 *
 * 1. get number of nodes from user
 * 2. dynamic alloc new matrix nxn
 * 3. create distance vector matrix, if dist > 1000 consider inf
 * _|   A   B   C   D   E   F
 * A|   0   5   2   3   i   i
 * B|   5   0   4   5   
 * C|
 * D|
 * E|
 * F|
 * ---------------
 *
 * 4. create new routing matrix of nxn
 * 5. create new minimizing array for the node
 * 6. find minimum of the array, allocate new value
 *
 * copyleft
 */

#define inf 1000

int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);

int main(){
    int n;                              //No of nodes
    int i,j;                            //Counters

    printf("> enter the number of nodes in the network... ");
    scanf("%d",&n);

    int **DisMat = (int **)malloc(n * n * sizeof(int));     //Dynamic allocation of Distance Matrix

    for(i=0; i<n; i++){                     // x directional loop
        printf("> distance vector table for node %c\n",i+65);
        for(j=0; j<n; j++){                 // y directional loop
            printf("> distance from %c... ",j+65);
            if(j==i) { DisMat[i][j] = 0; printf("0");}
            else scanf("%d",&DisMat[i][j]);
        }// y directional loop
    }// x directional loop

    int **NewDisMat = (int **)malloc(n * n * sizeof(int));      //New Distance Matrix
    char **Hop = (char **)malloc(n * n * sizeof(char));     //New Hop Matrix

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            Hop[i][j] = '-';                //All Hops Nullified
        }
    }

    dvr(DisMat, NewDisMat, Hop, n);                 //Distance Vector Routing

    return 0;
}//main

void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){     //DVR function
    int x=0, y=0, z=0, conCount;
    int hopPoint;
    int *mini = (int *)malloc((l-1) * sizeof(int));
    int *mzer = (int *)malloc((l-1) * sizeof(int));

    for(x=0; x<l; x++){                     // x directional propagation
        mini[0] = x;
        z = 1; conCount=0;
        do{
            if((dvt[x][y] < inf) && (y != x)) {
                mini[z] = y;
                z++;
                conCount++;
            }
            y++;
        }while(y<l);

        y = 0; z = 0;

        for(y = 0; y<l; y++){
            while(z<conCount){
                mzer[z] = dvt[mini[z]][y];
                z++;
            }

            newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
            hopper[x][y] = hopPoint + 65;
        }// y directional propagation
    }// x directional propagation
}//dvr

int min_r(int arr[], int *index, int len){
    //Sequential minimum search
    int min;
    int ind = 0;

    min = arr[ind];
    for(ind = 0; ind<len; ind++){
        if(arr[ind] < min){
            min = arr[ind];
            *index = ind;
        }
    }

    return min;
}//min_r

void dvtDisp(int *dvt[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d",dvt[x][y]);
    }
}

void dvtDispNew(int *dvt[], char *hopto[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c\thop",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
    }
}

执行期间我在终端上得到以下输出。

anwesh@bionic-Inspiron:~/Documents/NS2/LAB/prog5$ gcc main.c
anwesh@bionic-Inspiron:~/Documents/NS2/LAB/prog5$ ./a.out
> enter the number of nodes in the network... 5
> distance vector table for node A
Segmentation fault (core dumped)

我尝试在 gdb 上运行它,但无法弄清楚结果意味着什么。这是 gdb 输出:-

Starting program: /home/anwesh/Documents/NS2/LAB/prog5/a.out
> enter the number of nodes in the network... 5
> distance vector table for node A

Program received signal SIGSEGV, Segmentation fault.
0x000055555555487e in main ()
(gdb)

最初我认为这是与动态内存分配有关的问题,但我不知道确切原因。我多次检查了代码,看看是否有任何幼稚的错误,但我做不到。

请帮帮我!提前致谢。

最佳答案

线路

int **DisMat = (int **)malloc(n * n * sizeof(int));     //Dynamic allocation of Distance Matrix

无效。 DisMat是一个指向整数数组的指针数组。所以我们需要先分配n个指向int的指针:

int **DisMat = malloc(n * sizeof(int*));

然后我们需要n次分配n个int的数组:

for(size_t i = 0; i < n; ++i) {
    DisMat[i] = malloc(n * sizeof(int));
}

Hop 也是如此和NewDisMat

请记住,malloc 不会检查乘法溢出。

以下代码运行良好:

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

/* Date : 03/06/2018
 *
 * Algorithm
 *
 * 1. get number of nodes from user
 * 2. dynamic alloc new matrix nxn
 * 3. create distance vector matrix, if dist > 1000 consider inf
 * _|   A   B   C   D   E   F
 * A|   0   5   2   3   i   i
 * B|   5   0   4   5   
 * C|
 * D|
 * E|
 * F|
 * ---------------
 *
 * 4. create new routing matrix of nxn
 * 5. create new minimizing array for the node
 * 6. find minimum of the array, allocate new value
 *
 * copyleft
 */

#define inf 1000

int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);

int main(){
    int n;                              //No of nodes
    int i,j;                            //Counters

    printf("> enter the number of nodes in the network... ");
    scanf("%d",&n);

    int **DisMat = malloc(n * sizeof(*DisMat));     //Dynamic allocation of Distance Matrix
    assert(DisMat != NULL);
    for(size_t i = 0; i < n; ++i) {
        DisMat[i] = malloc(n * sizeof(*DisMat[i]));
        assert(DisMat[i] != NULL);
    }

    for(i=0; i<n; i++){                     // x directional loop
        printf("> distance vector table for node %c\n",i+65);
        for(j=0; j<n; j++){                 // y directional loop
            printf("> distance from %c... ",j+65);
            if(j==i) { DisMat[i][j] = 0; printf("0");}
            else scanf("%d",&DisMat[i][j]);
            printf("\n");
        }// y directional loop
    }// x directional loop

    int **NewDisMat = malloc(n * sizeof(*NewDisMat));      //New Distance Matrix
    assert(NewDisMat != NULL);
    for(size_t i = 0; i < n; ++i) {
        NewDisMat[i] = malloc(n * sizeof(*NewDisMat[i]));
    assert(NewDisMat[i] != NULL);
    }
    char **Hop = malloc(n * sizeof(*Hop));     //New Hop Matrix
    assert(Hop);
    for(size_t i = 0; i < n; ++i) {
        Hop[i] = malloc(n * sizeof(*Hop[i]));
        assert(Hop[i] != NULL);
    }

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            Hop[i][j] = '-';                //All Hops Nullified
        }
    }

    dvr(DisMat, NewDisMat, Hop, n);                 //Distance Vector Routing

    for(size_t i = 0; i < n; ++i) {
         free(DisMat[i]);
    }
    free(DisMat);
    for(size_t i = 0; i < n; ++i) {
         free(NewDisMat[i]);
    }
    free(NewDisMat);
    for(size_t i = 0; i < n; ++i) {
         free(Hop[i]);
    }
    free(Hop);
    return 0;
}//main

void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){     //DVR function
    int x=0, y=0, z=0, conCount;
    int hopPoint;
    int *mini = (int *)malloc((l-1) * sizeof(int));
    int *mzer = (int *)malloc((l-1) * sizeof(int));

    for(x=0; x<l; x++){                     // x directional propagation
        mini[0] = x;
        z = 1; conCount=0;
        do{
            if((dvt[x][y] < inf) && (y != x)) {
                mini[z] = y;
                z++;
                conCount++;
            }
            y++;
        }while(y<l);

        y = 0; z = 0;

        for(y = 0; y<l; y++){
            while(z<conCount){
                mzer[z] = dvt[mini[z]][y];
                z++;
            }

            newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
            hopper[x][y] = hopPoint + 65;
        }// y directional propagation
    }// x directional propagation
}//dvr

int min_r(int arr[], int *index, int len){
    //Sequential minimum search
    int min;
    int ind = 0;

    min = arr[ind];
    for(ind = 0; ind<len; ind++){
        if(arr[ind] < min){
            min = arr[ind];
            *index = ind;
        }
    }

    return min;
}//min_r

void dvtDisp(int *dvt[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d",dvt[x][y]);
    }
}

void dvtDispNew(int *dvt[], char *hopto[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c\thop",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
    }
}

旁注:请记住 sizeof(int*) == sizeof(*DisMat) ,所以我更喜欢:

int **DisMat = malloc(n * sizeof(*DisMat));

通过使用该表达式 type *variable = malloc(n * sizeof(*variable))我记得,我分配了正确的类型,在 DisMat 的情况下是一个指向整数的指针数组。 ,原因typeof(*DisMat) == int* ,并减少错误。

关于c - 具有动态内存分配的嵌套 for 循环中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668947/

相关文章:

c - 在嵌入式C中,如何将 "Unsigned Char"形式的返回十六进制值转换为可用的 "Integer"类型

c - 使文件错误

c - 加勒比在线法官期间运行时错误

javascript - 当父元素阻止冒泡时,不会触发 click 事件

model-view-controller - Ember.js 递归 Controller 和 View

c - 在为链表实现追加函数时出现段错误

python - 在 Python 上使用多进程与 API 请求和多个 for 循环

javascript - 嵌套 For 循环 - Javascript

python - 有没有更有效的方法来多次调用具有不同参数的函数?

javascript - 从动态生成的嵌套数组中获取值