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

Dani AI

Generated

correctly identified the real cause: the shifting index (position) was allowed to run out of range across iterations of the outer loop. When the outer loop runs more than once (inputs that need multiple zeros, e.g. lengths 4 or 7), a stale position value underflows and the code writes outside the character array, corrupting memory and producing a segmentation fault.

Moving the position initialization inside the while fixes the immediate crash, but a safer, clearer approach avoids manual byte-shifting and fixed-size buffers. Using std::string makes the intent obvious and eliminates most off-by-one and overlap issues. For example:

if (argc > 1) {
    std::string s = argv[1];
    std::size_t add = (3 - (s.size() % 3)) % 3;
    s.insert(0, add, '0');    // prepend required zeros in one operation
    std::cout << s << '\n';
}

If a C-style buffer must be used, take these precautions: ensure the buffer is large enough for the final result, recalculate position at each outer iteration, cache the length instead of calling strlen repeatedly inside loop headers, and prefer memmove for shifting overlapping memory. 's reminder to check argc is important too—missing arguments will also cause a segfault.

Running the program under Valgrind or AddressSanitizer will quickly show any out-of-bounds writes. After the small fix noted by (confirmed by ), the crash goes away; switching to the std::string pattern above makes the code robust and easier to maintain.

Recommended Answers

All 3 Replies

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.

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.

Thanks TheApex that got it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.