S
S
Stanislav Timoshko2020-10-27 22:42:18
C++ / C#
Stanislav Timoshko, 2020-10-27 22:42:18

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


}
}


Code 2 (not 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);
  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

1 answer(s)
R
Rsa97, 2020-10-27
@MooTs

for(i; i<75; i++)- the initial value of i is not initialized, with a high probability there will be a crash due to an attempt to write to someone else's memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question