In the following program everything works fine when I enter 5 or 8, but if I enter 4 or 7 the program crashes with a Segmentation fault error. I'm just trying to add zeros until the number of characters in string is evenly divisible by 3 and I'm doing so by padding it with zeros.

garrett@bedroom ~/Projects/TestArea $ ./addZeros 12345
12345
012345
garrett@bedroom ~/Projects/TestArea $ ./addZeros 1234
1234
Segmentation fault

#include<stdio.h>
#include<iostream>
#include<string.h>

int main(int argc, char *argv[])
{
    char string[10] = "";
    strcpy(string, argv[1]);
    std::cout << string << std::endl;



    int position = strlen(string);


    while(strlen(string) % 3 != 0 || strlen(string) < 3)
    {
        for(int i = 0; i < strlen(string); i++)
        {
            string[position + 1] = string[position];
            position--;

        }

        string[0] = '0';
    }

    std::cout << string << std::endl;

    return 0;
}

int position is probably reaching negative values, so you're trying to access a negative index of the string - this action might end up corrupting the memory so that's the reason why you would get Segmentation Fault.

Try moving the line 13 ( int position = strlen(string); ) inside the while loop, so it will update the position before entering the for loop.

Edited 3 Years Ago by TheApex

Your code compiles for me. Are you sure you're passing something in the arguments? If I enter "Hello" into the argument then I get the following:

Hello 0Hello

If no argument is passed through, this code will segment, you should allow for this.

This question has already been answered. Start a new discussion instead.