Can anyone tell me how can I solve the segmentation fault? I am still in a very early session of the class. I know that the segmentation fault has to do with my array and variable "storedplain". My intention was to create an array with int type and then store all the char variables that the user typed as int for my code in the next steps.
string plaintext = get_string(" plaintext: ");
int storedplain[] = {0};
for(int i = 0; i < strlen(plaintext); i )
{
char conversion2 = plaintext[i];
storedplain[i] = conversion2;
}
CodePudding user response:
int storedplain[] = {0};
is the same as int storedplain[1] = {0};
.
This means storedplain[i] = conversion2
will write past the end of storedplain
since i < strlen(plaintext)
will result in a value for i
larger than 0.
A solution would be something along the line of int storedplain[MAX_STRING] = {0};
. This could only work if you know the max string size that can be returned.
The best solution is to use malloc()
:
int * storedplain = malloc(strlen(plaintext) * sizeof(int));