I am trying to make a cipher program, and I am getting this error nearing the final steps of my cipher function (Really sorry if I'm not being any more clear, this is my first time asking/posting a question here, about a bloated code of mine)
Here is the code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
string ptoc(string ptext);
//Declaration of validated key as global so that Caesar(ptoc) function can access it
long int ckey;
int main(int argc, string argv[])
{
string *c;
string ctext;
string ptext;
if (argc != 2)
{
printf("Only enter the key\n");
return 1;
}
else if (argc == 2)
{
//Converting entered CL argument into integer
c = &argv[2];
long int key = strtol(argv[1], c, 10);
if (key == 0) //
{
printf("Enter a valid key, a positive integer\n");
return 1;
}
else // Assigning to another variable if valid
{
ckey = key;
}
printf("%ld\n", ckey);
}
ptext = get_string("Enter the plaintext: \n");
ctext = ptoc(ptext);
}
//Cipher function
string ptoc(string ptext)
{
string collect;
for (int i = 0, len = strlen(ptext); i < len; i++)
{
char c = ptext[i];
if (isalpha(c))
{
if (c == '.' || c == ',' || c == '!')
{
i++;
}
else if (isupper(c))
{
if (c >= 'A' && c <= 'Y')
{
sprintf(collect, "%i", c + 1);
}
else if (c == 'Z')
{
sprintf(collect, "%i", c - 24);
}
}
else if (islower(c))
{
if (c >= 'a' && c <= 'y')
{
sprintf(collect, "%i", c + 1);
}
else if (c == 'z')
{
sprintf(collect, "%i", c - 24);
}
}
}
}
return collect;
}
The error the compiler gives me is this:
Cae1.c:59:30: error: variable 'collect' is uninitialized when used here [-Werror,-Wuninitialized]
sprintf(collect, "%i", c + 1);
^~~~~~~
Cae1.c:44:19: note: initialize the variable 'collect' to silence this warning
string collect;
^
= NULL
What I don't get is why is the compiler saying the variable collect(which is a string) is uninitialized when I have initialized it within the right scope?
Sorry for the bloated mess again.
This declaration
string collect;
is equivalent to that declaration
char *collect;
due to the typedef
typedef char * string;
That is this declaration declares an uninitialized pointer that has an indeterminate value. And this pointer is used in calls like this
sprintf(collect, "%i", c + 1);
that results in undefined behavior.
As you are returning this pointer from the function ptoc
then you need to allocate dynamically a memory of an appropriate size to which the pointer will point to.
Something like
string collect = malloc( an_appropriate_size );