c - C 中的分配错误(函数或代码)和奇怪的行为

标签 c allocation calloc

我在尝试编写一个使用高斯消元法求解线性方程组的程序时偶然发现了这个问题。我对这么长的代码部分感到抱歉,但我确实需要帮助,我认为这样您就可以看到我是否犯了一些我忽略的错误。

这个程序工作得很好,直到我尝试将我的 b 矩阵或 c 矩阵命名为“解决方案”,并且我意外地发现了这一点,因为使用其他名称一切都工作得很好。 另外,如果我运行调试器,即使给出名称解决方案,也不会发生此故障 例如,当我给出此输入时: 系数矩阵行数:4 系数矩阵列:4 系数矩阵名称:Test

卢比。矩阵行数:4 卢比。矩阵列:1 卢比。矩阵名称:Rs

Solr 。矩阵行数:4 Solr 。矩阵列:1 Solr 。矩阵名称:溶液

程序崩溃了。 如果我为 Rs(b) 矩阵提供名称解,也会发生同样的情况。

如果我命名我的第一个矩阵解决方案,这种情况就不会发生,这真的很奇怪。另外,我的代码中还有另一种情况,它仅分配一个矩阵,并且该矩阵也可以命名为解决方案。

更奇怪的是,当这些错误发生时,有时但只是有时我的程序会打印消息“无法在崩溃之前为矩阵行分配内存”。我的输入始终保持不变 我还尝试将 calloc 更改为 malloc 等等..

提前致谢!

typedef struct matrix_s //This is the structure
{
char *name;
double **element;
long columns;
long rows;
}matrix_t;

matrix_t *matrix_allocate(long columns, long rows, char *name)//This is my function that fails
{
if(rows<=0 || columns<=0)
{
    fprintf(stderr,"Number of rows/columns is not valid\n");
    return 0;
}

matrix_t *mymatrix=calloc(1,sizeof(matrix_t));

long i;

if(!mymatrix)
{
    fprintf(stderr,"Failed to allocate memory for matrix\n");
    return 0;
}

mymatrix->name=calloc(strlen(name),sizeof(char));

if(!mymatrix->name)
{
    fprintf(stderr,"Failed to allocate memory for the name of matrix\n");
    free(mymatrix);
    mymatrix=0;
    return 0;
}

strcpy(mymatrix->name,name);


mymatrix->element=calloc(rows,sizeof(double *));


if(!mymatrix->element)
{
    fprintf(stderr,"Failed to allocate memory for matrix rows\n");
    free(mymatrix->name);
    mymatrix->name=0;
    free(mymatrix);
    mymatrix=0;
    return 0;
}

for(i=0;i<rows;i++)
{
    mymatrix->element[i]=calloc(columns,sizeof(double));

    if(!mymatrix->element[0])
    {
        fprintf(stderr,"Failed to allocate columns for the first row\n");
        free(mymatrix->name);
        mymatrix->name=0;
        free(mymatrix->element);
        mymatrix->element=0;
        free(mymatrix);
        mymatrix=0;
        return 0;
    }

    if(!mymatrix->element[i])        {
        fprintf(stderr,"Failed to allocate columns for the row     w     number:%ld\n",i);
        for(i=i-1;i>=0;i--)
        {
            free(mymatrix->element[i]);
            mymatrix->element[i]=0;
        }
        free(mymatrix->name);
        mymatrix->name=0;
        free(mymatrix->element);
        mymatrix->element=0;
        free(mymatrix);
        mymatrix=0;
        return 0;

    }


}

mymatrix->columns=columns;
mymatrix->rows=rows;

return mymatrix;
}


int main()//Short version of the main programm
{
    matrix_t *a=0, *b=0, *c=0;
    char matrixname[50];
    long rows,cols;

    ...

    case 5:
                       clearbuff();//while(getchar()!='\n')
            printf("Coeff. matrix rows:");
            scanf("%ld",&row);
            clearbuff();
            printf("Coeff. matrix columns:");
            scanf("%ld",&cols);
            clearbuff();
            printf("Coeff. matrix name:");
            fgets(matrixname,49,stdin);
            *strrchr(matrixname,'\n')=0;
            a=matrix_allocate(cols,row,matrixname);

            clearbuff();
            printf("Rs. matrix rows:");
            scanf("%ld",&row);
            clearbuff();
            printf("Rs. matrix columns:");
            scanf("%ld",&cols);
            clearbuff();
            printf("Rs. matrix name:");
            fgets(matrixname,49,stdin);
            *strrchr(matrixname,'\n')=0;
            b=matrix_allocate(cols,row,matrixname);

            clearbuff();
            printf("Sol. matrix rows:");
            scanf("%ld",&row);
            clearbuff();
            printf("Sol. matrix columns:");
            scanf("%ld",&cols);
            clearbuff();
            printf("Sol. matrix name:");
            fgets(matrixname,49,stdin);
            *strrchr(matrixname,'\n')=0;
            c=matrix_allocate(cols,row,matrixname);
            clearbuff():
            ....
            ....
            break;

}

最佳答案

您永远不会为nul 终止符分配空间。每需要 n 个字节 + 1,对于标记字符串结尾的特殊字符,此

const char example[] = "example"

相当于

const char example[] = {'e', 'x', 'a', 'm', 'p', 'l', 'e' ,'\0'};

您也经常使用 calloc(),但除了将每个字节初始化为 0 之外,您不需要使用 calloc() >,要为字符串分配空间,您可以这样做

char *copy;
size_t length;
length = strlen(original); // Only call `strlen()' once please
copy = malloc(length + 1);
if (copy == NULL)
    handle_error_and_stop_here();
memcpy(copy, original, length + 1);
//                              ^ copy the `nul' too

有一个函数可以为您完成此操作,简单

copy = strdup(original);

还要检查NULL,因为失败时它将返回NULL

关于c - C 中的分配错误(函数或代码)和奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643130/

相关文章:

c++ - Visual C++::'malloc' 中的奇怪错误:函数不带 1 个参数

c - 我正在研究图的连通性。为什么我会遇到段错误 : 11?

c - 将一个函数中矩阵的内容发送到另一个函数中的矩阵

xcode - Xcode 的调试导航器的工作方式与 Instruments 分配不同吗?

c++ - 自定义分配器,包括放置新案例

c - 获取分配的内存空间的特定长度的一部分

c - 在 C 中,数组(即字符串)中的字符是存储在单独的寄存器中还是每个寄存器有四个字符?

c - 为什么 calloc 不打算分配任意值?

c - 在 PowerPC 上实现断点读/写

c - 一个简单的对象系统