Malloc Signal: проблема SIGABRT (сигнал SIGABRT) - PullRequest
0 голосов
/ 19 мая 2019

У меня проблема с моим кодом, использующим malloc.Он работал отлично до часа назад.Это вызывает в этой строке

                    temp2 = (Temp*)malloc(sizeof(Temp));

Я пытался удалить (Temp *), чтобы увидеть, помогает ли это, но это не так.И когда я искал свое сообщение об ошибке

untitled8(15926,0x1141ae5c0) malloc: Incorrect checksum for freed object 0x7fbff3c032e8: probably modified after being freed.
Corrupt value: 0x742e7962616c6c61
untitled8(15926,0x1141ae5c0) malloc: *** set a breakpoint in malloc_error_break to debug
Signal: SIGABRT (signal SIGABRT)

Ответы, которые я нашел в интернете, имели какое-то отношение к free (), но раньше он вызывал ошибку, когда я освобождаю все недопустимые переменные.

У меня есть main.c и task1.c и task.2, а также файл заголовка 3, и приведенный ниже код взят из task1.c.Никогда не хотел публиковать этот длинный код, но так как я использовал malloc для другой части, я хотел бы, чтобы он также был проверен ... извините за любые неудобства, читая код заранее.

typedef struct histogramTemp {
    char *words;
    int count;
    struct histogramTemp *next;
} HistogramTemp;

typedef struct temp{
    char c;
    struct temp *next;
} Temp;


HistogramTemp *task1(FILE *fp, char *fname){

    char textfile, *string = NULL;

    Temp *tempHead = NULL, *temp1, *temp2;
    HistogramTemp *uniqueWordTemp = NULL, *headTemp, *uniqueWordTempHead = NULL;


    if(fp == NULL){
        printf("\n\n!! Error in opening file !!\n");
        printf("Program will proceed with defult 'australia.txt' file. \n");

        FILE *defultFp;
        defultFp = fopen("/Users/katyang/CLionProjects/untitled8/australia.txt", "r");

        fp = defultFp;

    }

    while((textfile = fgetc(fp))!=EOF){

        // save temporary word as a separate char linked list 'Temp', and save it to 'string' as a whole word

        if (isupper(textfile)>0) {
            temp1 = (Temp*)malloc(sizeof(Temp));
            temp1->c = textfile;

            temp1->next = tempHead;
            tempHead = temp1;

            int i=0;
            while(tempHead != NULL){
                string = malloc(30*sizeof(char));
                strcpy(&string[i],&tempHead->c);
                i++;
                tempHead = tempHead->next;
            }

            while ((textfile = fgetc(fp))!=EOF) {
                if (isalpha(textfile)>0 && !(isupper(textfile))) {
                    temp2 = (Temp*)malloc(sizeof(Temp));
                    temp2->c = textfile;

                    temp2->next = tempHead;
                    tempHead = temp2;

                    while(tempHead != NULL){
                        strcpy(&string[i],&tempHead->c);
                        i++;
                        tempHead = tempHead->next;
                    }
                }

                // use 'string', make Histogram
                if(isupper(textfile) || !isalpha(textfile)){

                    int flag=0;
                    int commonWordsFlag=0;

                    // check if the words are in the commonWords list
                    for (int j = 0; j < 122 ; j++) {
                        if (strcmp(string, commonwords[j])==0){
                            commonWordsFlag++;
                            break;
                        }
                    }

                    if((strlen(string)<3) || (commonWordsFlag == 1)){
                        break;
                    }

                    headTemp = uniqueWordTempHead;

                    // compare string to uniqueWordTemp
                    while (uniqueWordTempHead != NULL){

                        // increment count if the word is in Histogram
                        if(strcmp(uniqueWordTempHead->words, string)==0){
                            uniqueWordTempHead->count++;
                            flag++;
                            uniqueWordTempHead=uniqueWordTempHead->next;
                        }else{
                            uniqueWordTempHead=uniqueWordTempHead->next;
                            continue;
                        }
                    }

                    // create new node if the word is not in Histogram
                    if ((uniqueWordTempHead == NULL) && (flag == 0)){
                        uniqueWordTempHead = headTemp;

                        uniqueWordTemp = (HistogramTemp*)malloc(sizeof(HistogramTemp));
                        uniqueWordTemp->words = string;
                        uniqueWordTemp->count=1;

                        // insert in head
                        uniqueWordTemp ->next = uniqueWordTempHead;
                        uniqueWordTempHead = uniqueWordTemp;

                    }else{
                        uniqueWordTempHead = uniqueWordTemp;
                    }
                    break;
                }
            }
        }
    }


    createNewFile(fname, uniqueWordTempHead);

    free(string);
    free(tempHead);
    return(uniqueWordTempHead);

}

Итак, я ожидал сохранить данные в temp2 строке.Кажется, это работает с отладкой, что так странно ... У меня нет проблем при отладке, но моя программа заканчивалась кодом завершения 11 каждый раз, когда я запускаю программу.

Редактировать Я добавилmain.c и заголовочный файл task1 () для получения дополнительной информации.

main.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include "task1.h"
#include "task2.h"


int main() {

    FILE *fp;
    char *fname = malloc(sizeof(char));
    printf("\n\n:::::::::::::: TASK 1 ::::::::::::::\n\nPlease Enter the Full Path of the file: \n");
    scanf("%s", fname);
    fp = fopen( fname , "r");

    task1(fp, fname);
    HistogramTemp *uniqueWordTempHead = task1(fp, fname);
    task2(fp, fname);



    free(fname);
    free(uniqueWordTempHead);
    return 0;

}

заголовочный файл

#ifndef UNTITLED8_TASK1_H
#define UNTITLED8_TASK1_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


typedef struct histogramTemp {
    char *words;
    int count;
    struct histogramTemp *next;
} HistogramTemp;

typedef struct temp{
    char c;
    struct temp *next;
} Temp;

HistogramTemp *task1(FILE *fp, char *fname);

int countHistogram (HistogramTemp *head);
void printHistogram (HistogramTemp *head, FILE *fp);
void createNewFile(char *userFilename, HistogramTemp *head);



#endif //UNTITLED8_TASK1_H

1 Ответ

1 голос
/ 19 мая 2019

Вы не можете добавить только char к «строке», например:

    strcpy(&string[i],&tempHead->c);

strcpy() ожидает указатель на 1-й char "строки" в качестве 2-го параметра. В C "строка" - это массив из char, где хотя бы один char равен '\0'.

Использование

    string[i] = tempHead->c;

вместо этого и завершите string, выполнив

  string[i] = '\0';

Также здесь

          while(tempHead != NULL){
            string = malloc(30*sizeof(char));

string get allocate для каждой итерации перезаписывает точку, полученную в предыдущей итерации. Это приводит к огромной утечке памяти.

Больше распределения вне цикла.

Так вот

        while(tempHead != NULL){
            string = malloc(30*sizeof(char));
            strcpy(&string[i],&tempHead->c);
            i++;
            tempHead = tempHead->next;
        }

будет выглядеть так

        string = malloc(30*sizeof(char));
        i = 0;
        while(tempHead != NULL && i < 29){ // one less to be able to store the '0' terminator
            string[i] = tempHead->c;
            i++;
            tempHead = tempHead->next;
        }
        string[i] = '\0';  // store the '0' terminator
...