C 在简单循环上获取分段错误
我试图执行这段代码(是的,注释掉了这两行代码),但每次我都会遇到分段错误。 我不明白为什么。 (linux,gcc)C 在简单循环上获取分段错误,c,segmentation-fault,C,Segmentation Fault,我试图执行这段代码(是的,注释掉了这两行代码),但每次我都会遇到分段错误。 我不明白为什么。 (linux,gcc) #包括 #包括 #包括 int main(int argc,char*argv[]) { 字符*电流; while(strcmp(“99999999zz”,当前)!=0) { 对于(inti=0;i
#包括
#包括
#包括
int main(int argc,char*argv[])
{
字符*电流;
while(strcmp(“99999999zz”,当前)!=0)
{
对于(inti=0;i
您应该声明数组而不是指针并初始化它
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
double limit = pow(10, 10); /* calculating this every time in the loop may cause loss of performance */
char current[128] = ""; /* allocate enough memory and initialize */
while(strcmp("99999999zz", current) != 0)
{
for(int i = 0; i < limit; i++)
{
sprintf(current, "%010d", i);
printf("%s\n", current);
for(int a = 97; a <= 122; a++)
{
for(int j = 0; j < 10; j++)
{
//current[j] = (char)a;
//printf("%s\n", current);
}
}
}
}
}
#包括
#包括
#包括
int main(int argc,char*argv[])
{
double limit=pow(10,10);/*每次在循环中计算此值可能会导致性能损失*/
当前字符[128]=“”;/*分配足够的内存并初始化*/
while(strcmp(“99999999zz”,当前)!=0)
{
对于(int i=0;i
您应该声明数组而不是指针并初始化它
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
double limit = pow(10, 10); /* calculating this every time in the loop may cause loss of performance */
char current[128] = ""; /* allocate enough memory and initialize */
while(strcmp("99999999zz", current) != 0)
{
for(int i = 0; i < limit; i++)
{
sprintf(current, "%010d", i);
printf("%s\n", current);
for(int a = 97; a <= 122; a++)
{
for(int j = 0; j < 10; j++)
{
//current[j] = (char)a;
//printf("%s\n", current);
}
}
}
}
}
#包括
#包括
#包括
int main(int argc,char*argv[])
{
double limit=pow(10,10);/*每次在循环中计算此值可能会导致性能损失*/
当前字符[128]=“”;/*分配足够的内存并初始化*/
while(strcmp(“99999999zz”,当前)!=0)
{
对于(int i=0;i 对于(int a=97;a我无法相信后一种代码运行时不会出现问题。你很幸运!你的char*current
没有初始化。你认为current
指向什么?哦,后一种代码碰巧起作用了…@MikeCAT:事实上没有。UB最糟糕的影响之一就是不让程序崩溃和不被注意地传递。我无法相信eve后一个代码运行时没有问题。你很幸运!你的char*current
没有初始化。你认为current
指向什么?哦,后一个代码碰巧工作了…@MikeCAT:事实上没有。UB最糟糕的影响之一是没有崩溃程序和不被注意地传递。@M.M不,它被传递给strcmp()
在被sprintf()
写入@M.M No之前,它在被sprintf()写入之前被传递到strcmp()
。
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
double limit = pow(10, 10); /* calculating this every time in the loop may cause loss of performance */
char current[128] = ""; /* allocate enough memory and initialize */
while(strcmp("99999999zz", current) != 0)
{
for(int i = 0; i < limit; i++)
{
sprintf(current, "%010d", i);
printf("%s\n", current);
for(int a = 97; a <= 122; a++)
{
for(int j = 0; j < 10; j++)
{
//current[j] = (char)a;
//printf("%s\n", current);
}
}
}
}
}