malloc(): 顶部已损坏大小

9
我正在开发一个程序,用于解密文件中的某些文本行。首先,我创建了另一个源代码,要求输入移位和一些文本。源代码将文本加密并写入文件中。
然后,我尝试使用下面的代码 -另一个源代码- 解密指定的文件。获取文件名。从文件名获取移位值。使用caesar_decrypt函数的帮助将文件中写入的每个字符复制,移位shift的值 -反转凯撒加密,我也有这个函数。但是,给定的字符必须是ascii值在32到127之间,才能被转换为另一个ascii值在32到127之间的字符。
我定义了一个模数函数,封装了余数运算符 -正数的模数- 和负数的模数。我还定义了strip函数,它与python中的strip函数相同。除了空格,它删除所有文字。我还有getIn(),它是python中的input()。
我尝试通过打印和使用gdb进行调试。没有效果。我在stackoverflow上研究了这个主题。找到一个条目。答案没有解决我的具体问题。
注意:我复制了整个程序,因为我认为您需要必要的详细信息。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>

/*GETIN FUNCTION*/
char* getIn() 
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) 
    {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
        ch = 0;

        /* Check if we need to expand. */
        if (size <= index) 
        {
            size += sizeof(char);
            tmp = realloc(line, size);
            if (!tmp) 
            {
                free(line);
                line = NULL;
                break;
            }
        line = tmp;
        }

    /* Actually store the thing. */
    line[index++] = ch;
    }

    return line;
}
/*FUNCTION THAT CONVERTS TO NUMERIC CHARACTER, PRECURSOR OF DIGITS OF SHIFT*/
char make_numeric(char ch)
{
    if(ch<91 && ch>63) return ch-16;
    if(ch<123 && ch>95) return ch-48;
    if(ch<58 && ch>47) return ch;
    return ch+16;
}

 /*STRIP FUNCTION*/
char* strip(char* str,int length)
{
    char *start=str,*end=&str[length-1];

    while(*start>0 && *start<33 || *start==127) ++start;
    if(!*start) return start;

    while(*end>=0 && *end<33 || *end==127) --end;
    ++end;
    *end=0;

    return start;
}
/*DECRYPTOR FUNCTION*/
char *caesar_decrypt(char *message_to_decrypt, void *shift)
{   
    int length=strlen(message_to_decrypt),i;
    char* decrypted_message;

    if(!message_to_decrypt) return NULL;

    if(!(decrypted_message=calloc(length+1,sizeof(char)))) return NULL;

    for(i=0;i<length;++i)
    {
    decrypted_message[i]=mod((message_to_decrypt[i]-33-*((int*)shift)),94)+33;
    }

return decrypted_message;
}   

/*THE MAIN PROGRAM*/
int main()
{

int shift,len_chshift,init,len_filename,i=0;
char *chshift,*line=NULL,*decrypted_line,*stripped_line,chinit,chlen_chshift;
char *filename=NULL,*newfilename=NULL;
FILE *oldfile=NULL;
FILE *newfile=NULL;
size_t lenline,len=0;

printf("-9");
/*FILENAME*/
printf("Enter the file name: ");
/*printf("-8");*/
filename=getIn();
/*printf("-7");*/
if(!access(filename,F_OK))
{
    len_filename=strlen(filename);
    /*printf("-6");*/
    i=len_filename;
    while(filename[i]!='.') --i;        
    chlen_chshift=filename[i-1];
    chlen_chshift=make_numeric(chlen_chshift);
    len_chshift=chlen_chshift-48;
    /*printf("-5");*/
    chshift=calloc(len_chshift+1,1);
    /*NEWFILENAME*/
    newfilename=calloc(i+1,1);
    /*printf("-4");*/
    strncpy(newfilename,filename,i);
    /*printf("-3");*/
    strcat(newfilename,"(decrypted).txt");
    /*printf("-2");*/
    chinit=make_numeric(filename[0]);
    init=chinit-48;
    /*SHIFT*/
    i=0;
    /*printf("-1");*/
    while(i!=len_chshift)
    {
        chshift[i]=make_numeric(filename[(i+1)*init]);
        ++i;
    }
    /*printf("0");*/
    shift=atoi(chshift);

    /*printf("1");*/
    if(!(oldfile=fopen(filename,"r")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        exit(1);
    }
    /*printf("2");*/

    if(!(newfile=fopen(newfilename,"+ab")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        fclose(oldfile);
        exit(1);
    }
    while ((lenline = getline(&line, &len, oldfile)) != -1)
    {
        stripped_line=strip(line,lenline);
        decrypted_line=caesar_decrypt(stripped_line, &shift);
        if(!decrypted_line)
        {
            printf("Could not allocate memory\n");
            if(newfilename) free(newfilename);
            if(filename) free(filename);
            if(chshift) free(chshift);
            exit(1);
        }

        fprintf(newfile,"%s\n",decrypted_line);

        if(decrypted_line) free(decrypted_line);
        decrypted_line=NULL;

        free(line);
        line=NULL;
        stripped_line=NULL;
        decrypted_line=NULL;
    }
    free(line);
    line=NULL;
}
else
{
    printf("Cannot access the file.");
    if(filename) free(filename);
    exit(0);
}

if(newfilename) free(newfilename);
if(filename) free(filename);
if(chshift) free(chshift);

fclose(oldfile);
fclose(newfile);
return 0;
}

该程序需要创建一个文件,其内容是提供给用户的另一个文件的解密副本。然而,在第一个fopen之前,它会抛出异常。
malloc(): corrupted top size
Aborted (core dumped)

当我取消每个printf行的注释时,在getIn()和printf("-7")之间会出现相同的错误。当注释掉printf时,我观察到filename保存了由getIn()返回的写入值。因此,我认为getIn()不是问题所在。
编辑(1):我添加了2个缺失的头文件,但仍然引发相同的错误。
编辑(2):我删除了所有不必要的头文件。
编辑(3):既然被要求,我将尝试通过一个示例来说明:假设我有一个名为的文件。
2/b*A".txt

只需两行代码

%52
abcd

我将文件名输入程序。
1)在 . 之前的最后一个字符是",转换为数字 2 。我们理解移位是一个两位数。
2)第一个字符是启动器,即 2 ,需要重复跳过的字符数为 2 个。由于我们有两位数字的移位数,因此我们将跳过两个字符两次。
3)现在我们有字符b和A,分别转换为2和1。我们的移位是21。 第一个字符(37)向后移位到 n (110),依此类推,我们需要创建一个新文件,其中包含以下内容:
n~#
LMNO

我很感激任何帮助。提前谢谢您。此外,我提到的变量是特定区间内的任意字符。有关详细信息,请查看源代码,或建议您在本地工作,因为我提供了整个程序。
对于 ASCII 码: https://www.asciitable.com/ 如果您对凯撒密码感兴趣: https://en.wikipedia.org/wiki/Caesar_cipher

评论不适合进行长时间的讨论;此对话已被移至聊天室 - Bhargav Rao
@HakanDemir,文件名中不能包含“/”。 - S.S. Anne
1个回答

13

您在 newfilename 中遇到了缓冲区溢出问题:

/* here you declare that the string pointed to by newfilename may contain `i`
   chars + zero-termination...*/ 
newfilename=calloc(i+1,1);

/* Here `i` is less than `strlen(filename)`, so only i characters from `filename`
   will be copied, that does NOT include the zero-termination
   (but it will be zero-terminated because the last byte in the buffer was 
   already cleared by `calloc`) */ 
strncpy(newfilename,filename,i);


/* Here `newfilename` is full, and `strcat` will write outside buffer!! Whatever
   happens after this line is undefined behaviour */   
strcat(newfilename,"(decrypted).txt");

因此,您必须为newfilename分配足够的空间:

newfilename = calloc (i + strlen("(decrypted).txt") + 1, 1);

在使用 strncpy 后,newfilename 可能没有以 null 结尾,对其进行 strcat 操作是未定义的行为。 - kiran Biradar
1
@kiran。不,newfilname 将会以零结尾。由于calloc()strncpy()之前分配了所有字节,因此所有字节都为零,并且我们在缓冲区容纳i+1字节的同时复制最大的i字节。 - HAL9000
哎呀,我没看到那部分。UV 提醒一下。 - kiran Biradar
@kiran,我之前发表的评论是错误的(因为很久以前写了答案)。但是这个声明是正确的,“newfilename”在使用“calloc(i+strlen("(decrypted).txt")+1, 1)”时将会被零终止。然后缓冲区将足够大以供“strncpy()”,“strcat()”和零终止使用。 “i + 1”的缓冲区大小是为了指出原始代码中的错误。 - HAL9000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接