我正在尝试执行此代码(是的,将两行注释掉),但每次我都会遇到分段错误。 我不明白为什么。 (linux,gcc)
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *current;
while(strcmp("99999999zz", current) != 0)
{
for(int i = 0; i < pow(10, 10); 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);
}
}
}
}
}
相反,此代码运行没有问题:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *current;
while(strcmp("99999999zz", current) != 0)
{
for(int i = 0; i < pow(10, 10); i++)
{
sprintf(current, "%010d", i);
printf("%s\n", current);
}
}
}
答案 0 :(得分:3)
您使用具有自动存储持续时间的未初始化变量值在两个程序中调用未定义行为,这是不确定的。
你应该声明一个数组而不是指针并初始化它。
#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);
}
}
}
}
}