On 26 Sep 2002, Mandar Khanolkar wrote:
> Allocate memory for arg[] before gets().
> Use malloc().
thx guys 4 the suggestions.
i've added the following code :
But still i get the same error (Segmentation Fault)
Also curious:
How come the program runs perfectly in DOS without allocating memory ?
/*
Now Allocate memory for arg[4]
I dunno why the following doesn't work:
if ((arg = (char *) malloc (30)) == NULL)
Compiler gives the error:
incompatible types in assignment
Is there some other method to allocate memory to array of
pointers?
*/
if ((*arg = (char *) malloc (30)) == NULL)
{
printf ("Error allocating memory \n");
exit (1);
}
P.S.
I know this is not the right place to discuss C programming but guys pls
bear with me ...
--
Nikhil Joshi
/* Program to Encrypt A file */
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int
main (int argc, char *argv[])
{
void crypt ();
char *arg[4];
if (argc != 4)
/* if no arguments or wrong nunber of arguments then take i/p interactively */
{
/* Now Allocate memory for arg[4]
I dunno why the following doesn't work:
if ((arg = (char *) malloc (30)) == NULL)
Compiler gives the error:
incompatible types in assignment
Is there some other method to allocate memory to array of pointers?
*/
if ((*arg = (char *) malloc (30)) == NULL)
{
printf ("Error allocating memory \n");
exit (1);
}
printf ("Please enter password\n");
gets (arg[1]);
/*
umm.. gets () ..
it is dangerous but heck we wont b runnin this prog on
some important server ;)
OK will try fgets()
*/
printf ("Please enter the file to be encrypted/decrypted\n");
gets (arg[2]);
printf ("Please enter the output filename\n");
gets (arg[3]);
crypt (arg);
}
else
crypt (argv);
free (arg);
printf ("\n Success! \n");
return 0;
}
void
crypt (char *cr_arg[])
{
FILE *fi, *fo;
char *cp;
int c;
if ((cp = cr_arg[1]) == NULL)
{
printf ("Invalid password\n");
exit (1);
}
if ((fi = fopen (cr_arg[2], "rb")) == NULL)
{
perror ("Unable to open input file ");
exit (1);
}
if ((fo = fopen (cr_arg[3], "wb")) == NULL)
{
perror ("Unable to create output file ");
exit (1);
}
while ((c = getc (fi)) != EOF)
{
if (!*cp)
cp = cr_arg[1];
c ^= *(cp++);
putc (c, fo);
}
fclose (fo);
fclose (fi);
return;
}