Answer the question
In order to leave comments, you need to log in
How to fix weird C code errors?
I tried to implement the enigma algorithm (encryption machine) in C. There are 6 arrays[75] that need to be randomly filled with numbers from 0 to 74, and they should not be repeated. I have written a function that performs this action by using a pseudo-random number generator function. With one array, everything works fine, it is filled as needed. When this function is called several times (to fill 6 arrays) some kind of devilry starts to happen. The program hangs, sometimes a segmentation error crashes, GNU Debugger starts skipping lines of code, it also hangs. What can it be and what can it be connected with?
[SOLVED]: All due to uninitialized variables
Code 1 (working):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char enigma();
void filling(int *, int);
void main()
{
enigma();
}
char enigma()
{
int reflector[75], rotor1[75], rotor2[75], rotor3[75], rotor4[75], rotor5[75];
filling(reflector, 5);
}
void filling(int rotor[], int randvalue)
{
int tmp;
int number;
int findflag;
int launchflag = 1;
int i;
srand(randvalue);
while(launchflag)
{
tmp = rand()%75;
for(i; i<75; i++)
{
if(rotor[i]==tmp)
{
findflag = 1;
break;
}
}
if(findflag==0)
{
rotor[number] = tmp;
number++;
i=0;
}
if(findflag==1)
{
i=0;
findflag = 0;
}
if(number == 74)
{
launchflag = 0;
}
}
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char enigma();
void filling(int *, int);
void main()
{
enigma();
}
char enigma()
{
int reflector[75], rotor1[75], rotor2[75], rotor3[75], rotor4[75], rotor5[75];
filling(reflector, 5);
filling(rotor1, 6);
filling(rotor2, 7);
filling(rotor3, 8);
filling(rotor4, 9);
filling(rotor5, 10);
}
void filling(int rotor[], int randvalue)
{
int tmp;
int number;
int findflag;
int launchflag = 1;
int i;
srand(randvalue);
while(launchflag)
{
tmp = rand()%75;
for(i; i<75; i++)
{
if(rotor[i]==tmp)
{
findflag = 1;
break;
}
}
if(findflag==0)
{
rotor[number] = tmp;
number++;
i=0;
}
if(findflag==1)
{
i=0;
findflag = 0;
}
if(number == 74)
{
launchflag = 0;
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question