views:

77

answers:

1

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';


}
+4  A: 
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.

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