简体   繁体   English

由于指针导致的C分段错误

[英]Segmentation Fault in C due to pointer

I have recently started coding in C, and am doing some stuff on project Euler. 我最近开始用C语言进行编码,并且正在Euler项目中做一些工作。 This is my code for challenge three so far. 到目前为止,这是我用于挑战三的代码。 The only problem is when I run the compiled code it throws a segmentation fault. 唯一的问题是,当我运行编译后的代码时,它将引发分段错误。 I think it may be due to a pointer I called, the suspect pointer is underneath my comment. 我认为这可能是由于我调用了一个指针造成的,可疑指针位于我的注释下方。 I did some research into the subject but I cant seem to be able to fix the error. 我对该主题进行了一些研究,但似乎无法修复该错误。 Any advice? 有什么建议吗?

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

bool is_prime(int k);
int * factors(int num);

int main(){
    int input;
    while (true){
        printf("Enter a number to get the prime factorization of: ");
        scanf("%d", &input);
        if (is_prime(input) == true){
            printf("That number is already prime!");

        }else{
            break;
        }
    }

    //This is the pointer I think is causing the problem
    int * var = factors(input);
    int k;
    for (k = 0; k < 12; k++){
        printf("%d", var[k]);
    }
}

bool is_prime(int k){
    int i;
    double half = ceil(k / 2);
    for (i = 2; i <= half; i++){
        if (((int)(k) % i) == 0){
            return false;
            break;
        }
    }
    return true;
}

int * factors(int num){
    int xi;
    static int array[1000];
    int increment = 0;
    for (xi = 1;xi < ceil(num / 2); xi++){
        if (num % xi == 0){
            array[increment] = xi;
            increment++;
        }
    }
}     

The factors function has no return statement. factors函数没有return语句。 It's supposed to return a pointer but it doesn't return anything. 它应该返回一个指针,但不返回任何东西。

Side note: Enable your compiler's warnings (eg, with gcc -Wall -Wextra ). 旁注:启用编译器的警告(例如,使用gcc -Wall -Wextra )。 If they're already enabled don't ignore them! 如果已启用它们,请不要忽略它们!

Your function is declared as 您的函数声明为

int * factors(int num);

but it's definition doesn't return anything and yet you are using it's return value in assignment. 但它的定义不返回任何内容,但您正在赋值中使用它的返回值。 This triggers undefined behavior . 这将触发未定义的行为 It will compile if compiled without rigorous warnings and the return value will most likely be whatever random value happened to be left in the return register (eg EAX on x86). 如果在没有严格警告的情况下进行编译,它将进行编译,并且返回值很可能是返回寄存器中保留的任意随机值(例如x86上的EAX)。


C-99 Standard § 6.9.1/12 Function definitions C-99标准§6.9.1 / 12 功能定义

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. 如果到达终止函数的},并且调用者使用了函数调用的值,则该行为未定义。

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

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