简体   繁体   English

动态 memory 分配中的分段错误(核心转储)错误

[英]Segmentation fault (core dumped) error in dynamic memory allocation

I'm new to coding and new to C++.我是编码新手,也是 C++ 新手。 I am trying to write code in which one enters elements of the matrix.我正在尝试编写一个输入矩阵元素的代码。 Afterwards, one column should be removed, and one row should be added.之后,应删除一列,并添加一行。 Removing one column works fine.删除一列工作正常。 However, after reallocating memory for the new number of rows, I get the message: segmentation fault (core dumped).但是,在为新的行数重新分配 memory 后,我收到消息:分段错误(核心转储)。 I am using pointers to create and edit my matrix.我正在使用指针来创建和编辑我的矩阵。 Here is my code.这是我的代码。 Thanks for any help!谢谢你的帮助!

#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,r,**p,column,row;
printf("Enter the number of rows and columns:\n");
scanf("%d\n%d",&r,&c);
p=(int**)calloc(r,sizeof(int*));
if(p==NULL) printf("Memory not allocated.\n");
else{
    for(int i=0;i<r;i++){
        *(p+i)=(int*)calloc(c,sizeof(int));
        printf("Enter %d. row\n",i+1);
        for(int j=0;j<c;j++){
            scanf("%d",*(p+i)+j);
        }
    }
    printf("Original matrix:\n");
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            printf("%d ",*(*(p+i)+j));
        }
        printf("\n");
    }

    printf("Which column do you want to remove?");
    scanf("%d",&column);
    while(column<1||column>c){
        printf("Wrong entry, enter again:");
        scanf("%d",&column);
    }
    for(int i=0;i<=r-1;i++){
        for(int j=column-1;j<=c-2;j++)
            *(*(p+i)+j)=*(*(p+i)+j+1);
        *(p+i)=(int*)realloc(*(p+i),(c-1)*sizeof(int));
    }
    printf("Matrix without %d. column:\n",column);
    for(int i=0;i<r;i++){
        for(int j=0;j<c-1;j++)
            printf("%d ",*(*(p+i)+j));
        printf("\n");
    }
    printf("Which row do you want to replace?\n");
    scanf("%d",&row);
    while(row<1||row>r){
        printf("Wrong entry, enter again:\n");
        scanf("%d",&row);
    }
    p=(int**)realloc(p,(r+1)*sizeof(int*));
    if(p==NULL)
        printf("Memory not allocated.\n");
    else{
        printf("Enter %d. row",row);
        for(int i=r+1;i>row-1;i++){
            *(p+i)=*(p+i-1);
        }
        for(int j=0;j<c-2;j++)
            scanf("%d",*(p+row-1)+j);
        printf("New matrix:\n");
        for(int i=0;i<=r;i++){
            for(int j=0;j<c-2;j++)
                printf("%d ",*(*(p+i)+j));
            printf("\n");
        }
    }
    }
    return 0;
    }

When you realloc memory for p , you add one new row to that array (one additional pointer).当您为p重新分配 memory 时,您会向该数组添加一个新行(一个额外的指针)。 But you never allocate the memory for that new row, and eventually you access this uninitialized pointer.但是您永远不会为该新行分配 memory,最终您访问了这个未初始化的指针。

But that's not the real problem.但这不是真正的问题。 In the loop where you want to bump the pointers up to make space for the inserted row, your initial value and loop increment are both wrong.在循环中,您要向上提升指针以为插入的行腾出空间,您的初始值和循环增量都是错误的。 With an initial value of int i=r+1 , the first write to *(p+i) will access one past the allocated space (which would be p[0] thru p[r] ).使用int i=r+1的初始值,第一次写入*(p+i)将访问已分配空间(即p[0]p[r] )之后的一个空间。 The loop increment should be a decrement, --i .循环增量应该是减量, --i Once this loop is done, then you can allocate space for the new row.完成此循环后,您可以为新行分配空间。

As other people here have stated, it is definitely easier to do this using std::vector.正如这里的其他人所说,使用 std::vector 绝对更容易做到这一点。

However, I assume you are doing this as a learning exercise so I would definitely recommend you to finish this and understand where you went wrong.但是,我假设您将其作为学习练习,因此我绝对建议您完成此操作并了解您出错的地方。 You were close, it looks like you just got confused with your indices.你很接近,看起来你只是对你的索引感到困惑。 Try using more descriptive variable names and splitting stuff into functions to make it harder to get lost in your own code.尝试使用更具描述性的变量名称并将内容拆分为函数,以使其更难迷失在自己的代码中。

I modified your code to get it to do what i think you were trying to do.我修改了你的代码,让它做我认为你想做的事情。 Take a look and let me know if that was helpful.看看,让我知道这是否有帮助。

But yes, if you do any future C++ work, avoid doing C style malloc, alloc, free, etc... and consider working with the std libs.但是,是的,如果你将来做任何 C++ 工作,请避免做 C 风格的 malloc、alloc、free 等......并考虑使用标准库。

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

int main()
{
    int c, r, ** p, column, row;
    printf("Enter the number of rows and columns:\n");
    scanf_s("%d\n%d", &r, &c);
    p = (int**)calloc(r, sizeof(int*));
    if (p == NULL) printf("Memory not allocated.\n");
    else {
        for (int i = 0; i < r; i++) {
            *(p + i) = (int*)calloc(c, sizeof(int));
            printf("Enter %d. row\n", i + 1);
            for (int j = 0; j < c; j++) {
                scanf_s("%d", *(p + i) + j);
            }
        }
        printf("Original matrix:\n");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                printf("%d ", *(*(p + i) + j));
            }
            printf("\n");
        }

        printf("Which column do you want to remove?");
        scanf_s("%d", &column);
        while (column<1 || column>c) {
            printf("Wrong entry, enter again:");
            scanf_s("%d", &column);
        }
        for (int i = 0; i <= r - 1; i++) {
            for (int j = column - 1; j <= c - 2; j++)
                * (*(p + i) + j) = *(*(p + i) + j + 1);
            *(p + i) = (int*)realloc(*(p + i), (c - 1) * sizeof(int));
        }
        c -= 1;
        printf("Matrix without %d. column:\n", column);
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++)
                printf("%d ", *(*(p + i) + j));
            printf("\n");
        }
        printf("Which row do you want to replace?\n");
        scanf_s("%d", &row);
        while (row<1 || row>r) {
            printf("Wrong entry, enter again:\n");
            scanf_s("%d", &row);
        }
        p = (int**)realloc(p, (r + 1) * sizeof(int*));
        if (p == NULL)
            printf("Memory not allocated.\n");
        else {
            printf("Enter %d. row", row);
            for (int i = 0; i < c; i++)
                scanf_s("%d", *(p + row -1) + i);
            printf("New matrix:\n");
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < c; j++)
                    printf("%d ", *(*(p + i) + j));
                printf("\n");
            }
        }
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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