3

So I have a program that works sometimes, but other times it doesn't. Sometimes putting in a printf statement will make the program magically work (and sometimes a printf will make it break). This makes me think I messed up as far as pointers/allocation goes, as I still have trouble wrapping my head around some things. The program is too long to post all the code, so I'll just show where I think the problem is.

I was given a function that takes a FILE* and a few char** as parameters, returning an int. The function is parsing a file, storing necessary strings to where the double pointers point to.

Here is how I used the function (alot of code is omitted/simplified):

char **s1;
char **s2;
char **s3;

int main(int argc, char ** argv){
    s1 = (char**)malloc(20);
    s2 = (char**)malloc(20);
    s3 = (char**)malloc(20);

    /* Unnecessary code omitted */
    read(inFile);
}

int read(FILE* in){
    /* omitted code */
    parse(in,s1,s2,s3);
    printf("%s",*s1); /* This is to show how I access the strings */
}

Im pretty sure that somewhere in my program, those strings are getting overwritten because I didn't allocate the memory properly. Hopefully my mistake is visible in the code snippet I gave, because I don't have many other theories for why my code doesn't work

2
  • 1
    You don't really need double pointers. You would need a double pointer if you had to allocate memory to the pointer inside the function.
    – Alok Save
    Commented Jan 27, 2013 at 5:30
  • 1
    as Alok said above you don't need the double pointers and also since this is tagged as C code you can also safely omit the casting at malloc
    – Lefteris
    Commented Jan 27, 2013 at 5:31

1 Answer 1

2

Since the API to parse() is specified with char ** I believe it is safe to assume that you really do need the double-indirection in the call, but not in the declaration.

So probably what you need is to skip the malloc() calls and say:

char *s1, *s2, *s3;
...
parse(in, &s1, &s2, &s3);

This would allow parse() to allocate its own space and return the three pointers to its caller by modifying the pointers themselves. I appreciate your efforts to distill the question to its core but it might be interesting to see the prototype for parse().

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.