realloc()的无效老大小 [英] realloc() invalid old size

查看:1044
本文介绍了realloc()的无效老大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的KandR C编程书乐趣的练习。该计划是寻找从一组由用户输入线最长行然后打印。

I am doing an exercise for fun from KandR C programming book. The program is for finding the longest line from a set of lines entered by the user and then prints it.

下面是我写(部分,有些部分是直接从书中获取): -

Here is what I have written (partially, some part is 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;
}

那一刻我输入一行超过10个字符,程序崩溃并显示: -

The moment I input more than 10 characters in a 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]

我还检查无效的realloc老大小但未能跟随传递指针的逻辑的指针的函数修改阵列

I also checked realloc invalid old size but could not follow the logic of passing a pointer to a pointer to the function modifying the array.

推荐答案

的realloc 呼叫通过采取一个指向一个存储区域上的<$ C将重新分配内存$ C>堆即调用的动态分配的内存结果的malloc

realloc call will re-allocate memory by taking a pointer to a storage area on the heap i.e a dynamically allocated memory result of a call to malloc.

在您的情况下,问题是,你通过调用的malloc 堆栈内存,而不是动态>这将导致在内存分配。而且,传递的指针自动字符数组 _getline 它使用它调用的realloc 。所以,你得到了错误。

In your case the problem is that you are allocating memory on the stack and not dynamically by a call to malloc which results memory allocation on the heap. And, passing the pointer of the automatic character array line to _getline which uses it for call to realloc. So, you got the error.

尝试动态分配的字符数组

Try dynamically allocating the character array line :

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

这篇关于realloc()的无效老大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆