Phoenix
Phoenix

Reputation: 181

Getting Segmentation Fault on simple loops

I'm trying to execute this code (yes, with that two lines commented out), but every time I get a Segmentation Fault. I can't understand why. (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);
            }
        }
    }
}
}

This code, instead, runs without problems:

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

Upvotes: 0

Views: 47

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You invoked undefined behavior in both programs by using value of uninitialized variable having automatic storage duration, which is indeterminate.

You should declare an array instead of a pointer and initialize it.

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

Upvotes: 3

Related Questions