Realloc () invalid old size

I am doing an exercise to enjoy the KandR C programming book. The program is designed to find the longest line from the set of lines entered by the user, and then print it.

Here is what I wrote (partially, part taken from the book directly): -

#include <stdio.h>
#include <stdlib.h>

int MAXLINE =  10;
int INCREMENT = 10;

void copy(char longest[], char line[]){
    int i=0;

    while((longest[i] = line[i]) != '\0'){
        ++i;
    }
}

int _getline(char s[]){
    int i,c;

    for(i=0; ((c=getchar())!=EOF && c!='\n'); i++){
        if(i == MAXLINE - 1){
            s = (char*)realloc(s,MAXLINE + INCREMENT);

            if(s == NULL){
                printf("%s","Unable to allocate memory");
                //  goto ADDNULL;
                exit(1);
            }

            MAXLINE = MAXLINE + INCREMENT;
        }
        s[i] = c;
    }

    if(c == '\n'){
        s[i] = c;
        ++i;
    }

ADDNULL:
    s[i]= '\0';
    return i;
} 

int main(){
    int max=0, len;

    char line[MAXLINE], longest[MAXLINE];

    while((len = _getline(line)) > 0){
        printf("%d", MAXLINE);
        if(len > max){
            max = len;
            copy(longest, line);
        }
    }

    if(max>0){
        printf("%s",longest);
    }

    return 0;
}

At the time of entering more than 10 characters per line, the program crashes and displays: -

*** Error in `./a.out': realloc(): invalid old size: 0x00007fff26502ed0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3d6a07bbe7]
/lib64/libc.so.6[0x3d6a07f177]
/lib64/libc.so.6(realloc+0xd2)[0x3d6a0805a2]
./a.out[0x400697]
./a.out[0x40083c]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x3d6a021b45]
./a.out[0x400549]

I also checked realloc with an invalid old size , but could not follow the logic of passing a pointer to a pointer to a function that modifies the array.

+4
source share
5 answers

realloc , heap i.e malloc.

, stack, , malloc, heap. , automatic line _getline, realloc. , .

line:

char* line  = (char *) malloc(MAXLINE); 
char* longest = ( char *) malloc(MAXLINE);
+6

invalid old size, , malloc/realloc " ". "" . , , realloc, , NULL, , malloc/calloc/realloc.

, realloc, , , . , line longest :

char *line = malloc(MAXLINE), *longest = malloc(MAXLINE);

, , free(line) free(longest) .

+4

_getline() 10 , realloc() , malloc(). undefined .

, , realloc(), _getline().

, , "0123456789\n". longest , , , realloc().

+1

realloc() , malloc(). .

, realloc() , - , , free(). realloc() , NULL, . realloc() temp, , realloc() .

+1

:

int _getline(char s[])

, _getline - , int char .

( , malloc() be NULL) .

, char.

.

free/realloc NULL . , malloc, calloc, realloc , .

0

Source: https://habr.com/ru/post/1547213/


All Articles