通过内存指针进行迭代时,C代码错误:EXC_BAD_ACCESScode = EXC_I386_GPFLT

如何解决通过内存指针进行迭代时,C代码错误:EXC_BAD_ACCESScode = EXC_I386_GPFLT

我正在为一个学校的C编程项目工作,它工作正常,但是现在突然之间,当它尝试访问numbers_array [j]下的内存块中的数字时,它将无法访问索引2。数组,并不断给我标题中的错误

我已经调试了大约一个小时,无法弄清楚出了什么问题。它将把编号为0的索引和编号为1的罚款作为因子,但是此后程序崩溃。知道有什么问题吗?

可以在注释Requirement 2下声明factor_struct后在循环中找到错误。

我的数字分解程序代码如下:

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

#define TRUE 1
#define FALSE 0

/* Requirement 2:
Creating a struct with serveral pieces of data */
struct factor_struct {
    int number,count;
    clock_t start;
    clock_t end;
    double time_to_factor;
    double times_array[];
};

/* Function header decleration */
void factor(struct factor_struct *fs);

/* The main program loop */
int main(int argc,const char * argv[]) {

/* Intializing the variables we'll be using during the run loop */
int input,number,continue_loop_one = TRUE,continue_loop_two = TRUE;
int *numbers_array;

/* Printing the welcome message to the screen */
printf("Welcome to Factor Factory!\n\n");

/* Asking how many numbers the user would like to factor*/
printf("How many different numbers would you like to factor?\n");

/* Start of LOOP_1: Ask user to input the amount of numbers to factor.
   This will let us allocate the proper amount of memory */
LOOP_1: do {
    printf("Please enter a number from 1 to 10: ");
    scanf("%d",&input);
    printf("\n");
    
    /* Check if user input is between 1 and 10,if not return to start of LOOP_1 */
    if(input < 1 || input > 10) {
        printf("%d isn't a valid number...don't play games with me human. Try again! \n\n",input);
        
        /* Need to flush the incorrect input from the buffer or else scanf will cause a continuous loop*/
        fflush(stdin);
        goto LOOP_1;
    }
    
    /* Break out of the loop and continue our program */
    continue_loop_one = FALSE;
    
} while (continue_loop_one == TRUE);

/* Requirement 4:
   Intialize our numbers array with the correct amount of memory */
numbers_array = (int*) calloc(input,sizeof(int));

/* Check if memory was allocated properly */
if (numbers_array == NULL) {
    printf("Error: Memory not allocated. Closing program...\n");
    exit(0);
}

/* Requirement 1:
   Asking the user to enter the numbers that we will be using our algorithm for to get their factors */
LOOP_2: do {
    printf("Excellent! Lets get started...");
    printf("enter %d number(s) between 2 and 1,000,000.\n",input);
    
    /* Variable to track how many numbers have been input just incase a user enters an invalid number*/
    int entered_number_count = 0;
    
    LOOP_3: for(int i = 0 + entered_number_count; i < input; i++) {
        printf("Number %d: ",i + 1);
        scanf("%d",&number);
    
        if (number < 2 || number > 1000000000) {
            printf("%d isn't a valid number...don't play games with me human. Try again! \n\n",number);
            fflush(stdin);
            goto LOOP_3;
        }
        
        /* Assinging a number to the value at the proper memory location in the numbers_array */
        numbers_array[i] = number;
        
        /* Incrementing the amount of entered numbers */
        entered_number_count++;
        }
    
    /* Break out the loop and continue our program */
    continue_loop_two = FALSE;
    
} while(continue_loop_two == TRUE);

printf("\n");

/* Requirement 2:
   Declaring our factor_struct for use */
struct factor_struct fs;
fs.count = 0;

/* For each number in the array,assign it to fs.number and factor it by passing it to our factor function
   Each pass over the array will reassign fs.number */

for(int j = 0; j < input; j++) {
    fs.number = numbers_array[j]; // **ERROR APPEARS IF INDEX J > 1**
    factor(&fs);
    fs.count++;
}

/* Requirement 3:
   Using a pointer to move through time_array which will calculate
   the total time to factor all numbers */
double total_time = 0.0;
double *ptr = fs.times_array;
for(; *ptr; ++ptr) { total_time += *ptr; }
printf("Total computation time: %f seconds. \n\n",total_time);

/* Ask the user if they would like to continue or quit the program*/
printf("Would you like to continue factoring numbers?\n");
printf("Enter 'y' to continue or 'q' to quit: ");

/* Control loop that handles the continue or quit commands */
char c;
while(c != 'q') {
    scanf("%c",&c);

    if(c == 'y') {
        printf("\n");
        goto LOOP_1;
    }
}

/* Thank the user and quit the program */
printf("\n");
printf("Thank you for using Factor Factory!\n");
printf("Closing program...\n\n");

/* Requirement 4:
   Deallocating the memory for the numbers_array */
free(numbers_array);
return 0;
}

/* Requirement 5:
Taking data and passing it through the facotring algorithm */
void factor(struct factor_struct *fs) {

/* Marking the starting time of the function */
fs->start = clock();

printf("Factors of %d: ",fs->number);

/* Algorithm for finding all factors of our number */
for(int i = 1; i <= fs->number/2; i++) {
    if (fs->number % i == 0) {
        printf("%d ",i);
    }
}

printf("%d\n",fs->number);

/* Marking the ending time of the function */
fs->end = clock();

/* Calculating the total time it took to find all factors*/
    fs->time_to_factor = (double)(fs->end - fs->start) / CLOCKS_PER_SEC;
    fs->times_array[fs->count] = fs->time_to_factor;
}

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

相关推荐


使用本地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-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res