由于指针导致的 C 中的分段错误
Segmentation Fault in C due to pointer
我最近开始用 C 编写代码,并且正在为 Euler 项目做一些事情。到目前为止,这是我挑战三的代码。唯一的问题是当我 运行 编译代码时它抛出一个分段错误。我认为这可能是由于我调用了一个指针,可疑指针在我的评论下方。我对该主题进行了一些研究,但似乎无法修复该错误。有什么建议吗?
#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++;
}
}
}
factors
函数没有 return 语句。它应该 return 一个指针,但它没有 return 任何东西。
旁注: 启用编译器的警告(例如,使用 gcc -Wall -Wextra
)。如果它们已经启用,请不要忽略它们!
您的函数声明为
int * factors(int num);
但它的定义没有 return 任何东西,但你在赋值中使用它的 return 值。这会触发 未定义的行为 。如果在没有严格警告的情况下编译,它将编译,并且 return 值很可能是 return 寄存器中碰巧留下的任何随机值(例如 x86 上的 EAX)。
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.
我最近开始用 C 编写代码,并且正在为 Euler 项目做一些事情。到目前为止,这是我挑战三的代码。唯一的问题是当我 运行 编译代码时它抛出一个分段错误。我认为这可能是由于我调用了一个指针,可疑指针在我的评论下方。我对该主题进行了一些研究,但似乎无法修复该错误。有什么建议吗?
#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++;
}
}
}
factors
函数没有 return 语句。它应该 return 一个指针,但它没有 return 任何东西。
旁注: 启用编译器的警告(例如,使用 gcc -Wall -Wextra
)。如果它们已经启用,请不要忽略它们!
您的函数声明为
int * factors(int num);
但它的定义没有 return 任何东西,但你在赋值中使用它的 return 值。这会触发 未定义的行为 。如果在没有严格警告的情况下编译,它将编译,并且 return 值很可能是 return 寄存器中碰巧留下的任何随机值(例如 x86 上的 EAX)。
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.