函数找不到失败的内存分配

如何解决函数找不到失败的内存分配

函数Control应该从二进制文件或文本文件(其名称保存在int load(const char *filename,int ***ptr,enum save_format_t format)指针下)中的数据加载到矩阵,而filename指向矩阵的指针下。文件扩展名取决于可变格式的值:0或1(在函数中,我显示了只有format = 0的选项,该选项主要用于文本文件,因为只有这一个会带来麻烦)。文件中正确的数据如下所示:

10 20 30 40 50 60 70 -1

100200300400500600700800-1

对于与上述示例完全相同的数据,应按以下方式加载数据:

ptr

这意味着每一行必须以'-1'结尾(数据必须以'-1'加载到矩阵)。指向最后一行之后的行的指针应等于NULL。

如果在任何情况下关闭功能分配失败,功能应返回4。

对扩展名为“ .bin”且堆限制的文件执行的测试返回此错误:

函数应返回4,但返回0。

我使用诸如int A[] = {10,20,30,40,50,60,70,-1}; int B[] = {100,200,300,400,500,600,700,800,-1}; int D[] = {A,B,C,NULL}; 之类的符号,因为不允许使用方括号。

有人可以帮助我如何使我的函数返回正确的整数。我的功能如下:

**ptr

解决方法

您的代码中存在多个问题:

  • if (i == h)似乎不正确:如果文件包含带有-1终止符的单行,即空矩阵,该怎么办?
  • temp = malloc(sizeof(temp) * (h + 1));应该是temp = malloc(sizeof(*temp) * (h + 1));
  • if (*(temp + i) != NULL) {读取malloc()分配的数组中的未初始化条目。应该删除测试,并且应该始终分配行。

这是修改后的版本:

int load(const char *filename,int ***ptr,enum save_format_t format) {
    if (filename == NULL || ptr == NULL || format != 0 && format != 1) {
        return 1;
    }
    int **temp = NULL;
    FILE *fp,*pp;
    if (format == 0) {
        int i = 0,x = 0,h = 0,w = 0,val = 0;
        fp = fopen(filename,"r");
        if (fp == NULL) {
            return 2;
        }
        pp = fopen(filename,"r");
        if (pp == NULL) {
            fclose(fp);
            return 2;
        }
        // determine the number of rows
        val = 0;
        while (fscanf(fp,"%d",&val) == 1) {
            if (val == -1)
                h++;
        }
        if (val != -1) {
            // empty file or file does not end with -1
            fclose(fp);
            fclose(pp);
            return 3;
        }
        temp = malloc(sizeof(*temp) * (h + 1));
        if (temp == NULL) {
            fclose(fp);
            fclose(pp);
            return 4;
        }
        fseek(fp,SEEK_SET);
        for (i = 0; i < h; i++) {
            w = 0;
            while (fscanf(pp,&val) == 1) {
                w++;
                if (val == -1)
                    break;
            }
            if (w == 0 || (*(temp + i) = malloc(sizeof(int) * w)) == NULL) {
                while (i-- > 0) {
                    free(*(temp + i));
                }
                free(temp);
                fclose(pp);
                fclose(fp);
                return 4;
            }
            for (x = 0; x < w; x++) {
                fscanf(fp,*(temp + i) + x);
            }
        }
        *(temp + h) = NULL;
        fclose(fp);
        fclose(pp);
    }
    *ptr = temp;
    return 0;
}
,

考虑读取字符串并使用strtol进行解析。
没有可用的RAM时,内存分配将返回NULL。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <math.h>

int load ( char const *filename,int ***ptr) {
    if ( filename == NULL || ptr == NULL) {
        return 1;
    }
    char entry[100] = "";
    char *end = NULL;
    int **temp = NULL;
    int *temprow = NULL;
    long int val = 0;
    int rows = 0;
    int cols = 0;
    int problem = 0;
    int result = 0;
    FILE* fp = NULL;

    fp = fopen ( filename,"r");
    if ( fp == NULL) {
        perror ( filename);
        return 2;
    }

    while ( 1 == ( result = fscanf ( fp,"%99s",entry))) {
        if ( -1 == val || ( 0 == rows && 0 == cols)) {
            if ( -1 == val) {
                ++rows;
            }
            if ( NULL == ( temp = realloc ( *ptr,sizeof **ptr * ( rows + 2)))) {
                fprintf ( stderr,"problem realloc *ptr\n");
                problem = 4;
                break;
            }
            *ptr = temp;
            *( ( *ptr) + rows) = NULL;
            *( ( *ptr) + rows + 1) = NULL;//sentinel

            cols = 0;
        }
        errno = 0;
        val = strtol ( entry,&end,10);
        if ( entry == end) {//nothing could be parsed to int
            problem = 3;
            break;
        }
        else if ( 0 != *end) {//extra characters after int
            problem = 3;
            break;
        }
        if ( ( errno == ERANGE && ( val == LONG_MAX || val == LONG_MIN))
        || ( errno != 0 && val == 0)) {// parsing error from strtol
            perror ( "input error");
            problem = 3;
            break;
        }
        if ( val > INT_MAX || val < INT_MIN) {
            problem = 3;
            break;
        }
        if ( NULL == ( temprow = realloc ( *( ( *ptr) + rows),sizeof ***ptr * ( cols + 2)))) {
            fprintf ( stderr,"problem realloc *( (*ptr) + row)\n");
            problem = 4;
            break;
        }
        *( ( *ptr) + rows) = temprow;
        ++cols;
        *( *( ( *ptr) + rows)) = cols;//save cols in index 0
        *( *( ( *ptr) + rows) + cols) = val;
    }
    fclose(fp);
    if ( 0 == result) {
        problem = 3;
    }
    return problem;
}

int main ( void) {
    char const *filename = "ints.txt";
    int **array = NULL;
    int row = 0;
    int each = 0;

    load ( filename,&array);

    row = 0;
    while ( array && ( *(array + row))) {
        each = 0;
        while ( each <= *( *(array + row))) {
            printf ( "%d\n",*( *(array + row) + each));
            ++each;
        }
        ++row;
    }

    row = 0;
    while ( array && ( *(array + row))) {
        free ( *(array + row));
        ++row;
    }
    free ( array);

    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-