Laith
Laith

Reputation: 81

Getting core dump freeing memory allocated by getline()

I am getting the core dump and I have been looking and it seems I am doing everything right.

int len = 0;
char *buff = NULL;
size_t sz;
if(getline(&buff,&sz, stdin) > 0){
    while(isalpha(*buff++))
        ++len;
       printf(" 1st word %d characters long ",len);
}
free(buff);

Upvotes: 0

Views: 99

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84579

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

You fail in (1) so you can't do (2). Specifically, what is happening is getline() allocates storage and assigns the beginning address for the allocated block to buff. You then use buff to iterate over the string calling *buff++. When you are done iterating, buff no longer points to (holds the beginning address of) the block of memory allocated by getline().

When you attempt to pass buff to free(), an error occurs because you are attempting to free an address that was not previously allocated by malloc, calloc or realloc.

Use a separate pointer to iterate with, e.g. char *p = buff; within your read loop and iterate with p. (you can also use an index for iterating, e.g. buf[i] without changing the original address buff holds) Then you can pass buff to free().

Upvotes: 5

Related Questions