0

Am I missing something incredibly simple? because I can't seem to find a reason why my code isn't storing strings dynamically. All I get are blank lines when I print them at the end. Its supposed to print the last "n" lines of an arbitrary number of lines. There seems to be a problem with the storage of the actual lines though. Can anyone lend a hand?

This is NOT HW by the way. This is a problem from the K&R book (whose answers are online). I'm trying to learn C on my own.

void tail5_13(int n)
{

    int maxpoint = 3;
    size_t *maxlength;
    *maxlength = sizeof(char) * 10;

    char **pointptr = malloc(sizeof(void *) * maxpoint);
    char **pointcnt = pointptr;

    char *lineptr = malloc(sizeof(char) * *maxlength);

    int numlines = 0;
    int printnum = 0;
    int c;



    while((c = getline(&lineptr, maxlength, stdin)) > 1)
    {
        if(numlines < maxpoint)
        {
            storeline5_13(pointcnt, lineptr, c);
            pointcnt++;
        }
        else
        {
            maxpoint *= 2;
            printf("Increased pointer amount to %d\n", maxpoint);
            pointptr = (char **) realloc(pointptr, sizeof(void *) * maxpoint);
            storeline5_13(pointcnt, lineptr, c);
            pointcnt++;
        }
        numlines++;
    }

    if(n <= numlines)
        printnum = n;
    else
        printnum = numlines;

    while(printnum-- > 0 )
    {
        printf("%s\n", *(pointcnt-1));
    }

}



void storeline5_13(char** pointcnt, char* line, int length)
{


    *pointcnt = (char *) malloc(sizeof(char) * length);

    while(*line != '\n')
    {
        *((*pointcnt)++) = *line++;

    }

    **pointcnt = '\0';


}
1
  • This is cross-posted in other forums too. Isn't it? Commented Oct 7, 2010 at 9:13

1 Answer 1

4
size_t *maxlength;
*maxlength = sizeof(char) * 10;

You're dereferencing a wild (unassigned) pointer.

Instead, it should be:

size_t maxlength = sizeof(char) * 10;
// ...
char *lineptr = malloc(sizeof(char) * maxlength);
// ...
while((c = getline(&lineptr, &maxlength, stdin)) > 1)

Then, you're just using an automatic variable.

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

1 Comment

Thanks! There were also 2-3 more small errors I've fixed. I've got the code working.

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.