I have a problem that I really can't understand. I'm a newbie C programmer, and I have a program that roughly goes like this:
void filetostr(FILE *, char *s[]);
void strtofile(char *s[], FILE *);
void XORstr(char *, int);
void XORtext(char *s[], int);
void printext(char *s[]);
int main(int args, char *argv[]) {
char *s[MAXLENGTH];
char ln[MAXLENGTH];
FILE *input, *xorred, *rexorred, *out;
input = fopen("input.txt", "r");
filetostr(input, s);
fclose(input);
printext(s);
XORtext(s, KEY);
}
void filetostr(FILE *fp, char *s[]) {
char ln[MAXLENGTH];
char *p;
int i = 0;
while (fgets(ln, MAXLINE, fp)) {
p = (char *) malloc(strlen(ln) * sizeof(char));
strcpy(p, ln);
s[i++] = p;
}
}
void printext(char *s[]) {
while (*s) {
printf("%s", *s);
s++;
}
}
void XORstr(char *s, int key) {
int c;
while (c = *s)
*s++ = key ^ c;
}
void XORtext(char *txt[], int key) {
while (*txt) {
XORstr(*txt, key);
txt++;
}
}
And I have two two problems:
- first, when I build the array of pointers to strings with
filetostr, I get it to work but two lines in the middle of the text are repeated (there are two references to them in the array, so withprintextthey get printed twice). How is that possible? Is there a wrong call to malloc? - second, when I try to XOR the lines I just mentioned, they get XORred only once, so I end up with a XORred line and a normal one for each duplicate line.
malloc()function.if(p == NULL) { /* no memory */ exit(1); }and 2) if there is enough space to storepinsarray; before ofs[i++] = p;:if(i >= MAXLENGTH) { /* no space to hold p in s */ }It may crash your application.