Im trying to make a simple encryption program, nothing mathematical or so but to go further I need to know what causes the segmentation fault in my program. I have tried to simplify my code..
char *
createAlfabeth(void)
{
char * alfa = NULL;
strcpy(alfa, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
int i, j=1, k=0;
for(i=0; i<(sizeof(alfa)/sizeof(char)); i++, j+=3)
{
if(j>25)
{
j=1+(k++);
}
swap(alfa, i, j);
}
return alfa;
}
char *
codificator(char *mess, const char *alfa)
{
int key[]=PRIVATE_KEY;
char *newmess=NULL;
int i, j;
for(i=0, j=0; mess[i]!='\0'; i++, j++)
{
if(j>(sizeof(key)/sizeof(key[0])))
{
j=0;
}
newmess[i]=alfa[i+key[j]];
}
return newmess;
}
int
main(void)
{
char *alfa=crearAlfabeto();
printf("write your message :\n");
char message[20];
scanf("%s", message);
char *codified=codificator(message, alfa);
printf("The codified message is: %s \n", codified);
return 0;
}
SOLVED: POST MEMORANDUM
I solved the problem with the recommendations by ouah and askmish below (thanks to both). And for you people googling to this answer, I want to say that this problem has to do with the heap handling. As I did not store enough space for the strings that I declared later or initialized there was not enough memory allocated to them.
This is was the malloc, realloc, calloc (and free) functions purpose is to handle. The segmentation fault comes from that I tried to move beyond the allocated memory for the data segment in the code. Every program allocated memory for the code (code segment), and data (data segment) and by not telling explicitly in c how much you are going to store in data segment you get this error. This is my understanding of what I have read, if someone with more insight wants to comment on this please do..
You need to allocate memory for your array object.
For example: