0

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 with printext they 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.
1
  • Also,don't forget to check 1) return-value from malloc() function. if(p == NULL) { /* no memory */ exit(1); } and 2) if there is enough space to store p in s array; before of s[i++] = p; : if(i >= MAXLENGTH) { /* no space to hold p in s */ } It may crash your application. Commented Jan 10, 2013 at 15:52

2 Answers 2

3
 p = (char *) malloc((strlen(ln) + 1) * sizeof(char));

instead of

 p = (char *) malloc(strlen(ln) * sizeof(char));

BTW, you can change

p = (char *) malloc((strlen(ln)+1) * sizeof(char));
strcpy(p, ln);
s[i++] = p;

by

s[i++] = strdup(ln)

It's the same

Sign up to request clarification or add additional context in comments.

3 Comments

But isn't strdup() POSIX?
This way where do I move along the array? Previously I did it with i++... Maybe I have to add s[i++] = p; after the strdup function?
sorry I make a mistake in my answer it should be s[i++] = strdup(ln). I will update the answer
1

The malloc in filetostr isn't quite right. It should be

p = malloc(strlen(ln) + 1);

You need to allocate space for the terminating null character, don't need to cast the return and can rely on sizeof(char) being 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.