c - 在简单循环中获取段错误

标签 c segmentation-fault

我正在尝试执行此代码(是的,将这两行注释掉),但每次我都会遇到段错误。 我不明白为什么。 (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);
    }
}
}

最佳答案

您通过使用具有自动存储持续时间的未初始化变量的值调用了两个程序中的未定义行为,这是不确定的。

你应该声明一个数组而不是一个指针并初始化它。

#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);
                }
            }
        }
    }
}

关于c - 在简单循环中获取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002056/

相关文章:

c++ - 确定 GetElementPtr 的字节偏移量

C 信号(SIGSEGV)为什么会无限循环?

更改不相关的代码会导致段错误。它为什么要这样做?

在 C 中将函数作为 float 调用

c - 如何比较C中指向字符串的指针

c - 直接返回地址时出现段错误,但通过指针返回地址时没有错误

c - C 中的 strtok 错误

c++ - LLVM IR 代码生成段错误仅在方法声明具有参数时退出

C 使用伯克利套接字发送文件

c - 在汇编中添加两个数字