0

The follow part of code worked perfectly, while I declared variables key_num and plaintext within if{}, but since I declared them outside (cause I need to use these vars later) I get the "Segmentation fault" error.

What am I doing wrong?

This code worked perfect:

if (argc == 2 && atoi(key))                
{
    int key_num = atoi(key);              
    string plaintext = get_string("plaintext: ");
}
else
{
    printf("Usage: ./caesar key\n");
}

And This code is getting the error:

int key_num = 0;
string plaintext = NULL;

if (argc == 2 && atoi(key))                 
{
    key_num = atoi(key);                
    plaintext = get_string("plaintext: ");
}
else
{
    printf("Usage: ./caesar key\n");
}
1
  • Your question does not have enough code for a definitive response. It's possible the segmentation fault happens when you try to print of modify plaintext. If that variable is NULL as you initially set to, then trying to write to it would result in a seg fault. It's also possible the seg fault happens when you call atoi. if your variable key is a character and not a pointer to a string, then you'll most likely touch memory you don't own. Oct 21 at 9:55
1

Strings are immutable. That means that when they are declared, the memory allocated to them cannot be changed. You can put a shorter string in that memory, but not a longer one because it will overwrite other memory allocated elsewhere.

When plaintext is declared in the second code snipet, it has exactly one byte allocated to it, to hold the end of string marker. Later when the code tries to store text there, it exceeds allocated memory, creating a string fault. The trick here is to change the code structure.

There's another lesson to learn here. It's a common newbie mistake to check that input data is valid and to enclose all the program code inside an if code block, as was done here. Commonly, the exit code is put in an else statement that follows way down in the code, again as was done here. The problem is that this type of coding makes it easy to introduce bugs later in development or code maintenance because the tasks that the code does is too intertwined.

The best practice is to check whether the input is NOT valid and to put exit code inside the if code block. This compartmentalizes the error checking into a few lines instead across much of the program. Here's the concept in practice:

if (argc != 2 ) 
{
    printf("Usage: ./caesar key\n");
}

// insert some code to make sure that key is all digits 
// and any other validation that may be needed.  
//  BTW, how did key get loaded?  Maybe validate argv[1] first?

int key_num = atoi(key);              
string plaintext = get_string("plaintext: ");
...

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .