IneptusMechanicus
IneptusMechanicus

Reputation: 508

An issue allocating data in c

I've got this homework, which is to make an implementation of the "tail" command in Linux and this is what i have so far:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>

char *resize(char *data, int size)
{
    char *newData = malloc((size + 1) * sizeof(char));
    int counter;

    for(counter = 0; counter < size; counter++)
        newData[counter] = data[counter];
    return newData;
}

char *readStdIn(char *data)
{
    char buff, end = '\n';
    int rState, size = 1;
    data = malloc(size * sizeof(char));

    printf("%ld\n", sizeof(data));
    while ((rState = read(STDIN_FILENO, &buff, 1)) > 0)
    {
        if(rState < 0)
        {
            if(errno == EINTR) rState = 0;
            else
            {
                perror("read()");
                return 0;
            }
        }
        data = resize(data, size);
        data[size - 1] = buff;
        size++;
    }
    printf("%ld\n", sizeof(data));
    if(rState == 0) write(STDOUT_FILENO, &end, 1);
    return data;
}

int printLines(char *data)
{
    int lines = 0, position;// counter;
    for(position = sizeof(data) - 1; position > -1; position--);
        if (data[position] == '\n') lines++;
    return 0;
}


int main(int argc, char *argv[])
{
    char *data = 0;
    if(argc == 1)
    {
        readStdIn(data);
        if(data == 0) return 1;
        if(printLines(data) != 0) return 1;
    }
    return 0;
}

In readStdIn() I'm supposed to save what i have read in the standard input and put it in char* data, so that i can find the last 10 lines(or find that there are less than 10 lines) of the input. The problem is, that when i call resize(), data doesn't resize, and I can't find out why. It's most likely a problem in the resize() itself, but i can't figure it out. The idea is that resize() increases the size of data by 1 char. I hope I was thorough enough in my explanation.

Upvotes: 0

Views: 53

Answers (1)

merlin2011
merlin2011

Reputation: 75589

Your printf is incorrect. You are printing the size of a pointer, which will be a fixed number depending on your architecture. You should instead print out the size directly.

printf("%d\n", size);

Your resize is correct except that you failed to free the previous memory, so you have a memory leak. You can fix this by adding a free() before you return.

char *resize(char *data, int size)
{
    char *newData = malloc((size + 1) * sizeof(char));
    int counter;

    for(counter = 0; counter < size; counter++)
        newData[counter] = data[counter];
    free(data);
    return newData;
}

Upvotes: 2

Related Questions