Функция realloc отказывается выделять память - C (СИ)

Узнай цену своей работы

Формулировка задачи:

#include <stdio.h>
#include <stdlib.h>
 
#define MAX_WORD_LENGTH 20
#define SMALLEST_CHAR   0
#define LARGEST_CHAR    255
#define ERROR           -1
 
int ReadCurrentWord(int *pWord);
void WriteWord(int *pWord);
void CompareWithLargest(int *pCurrentWord, int *pLargestWord);
void CompareWithSmallest(int *pCurrentWord, int *pSmallestWord);
 
int main()
{
    int *currentWord = NULL;
    int smallestWord[MAX_WORD_LENGTH + 1] = {LARGEST_CHAR};
    int largestWord[MAX_WORD_LENGTH + 1] = {SMALLEST_CHAR};
    int wordLength;
 
    do
    {
        printf("Enter word: ");
 
        if ((wordLength = ReadCurrentWord(currentWord)) == ERROR)
        {
            printf("Error allocation memory");
            return ERROR;
        }
        else if (wordLength > MAX_WORD_LENGTH)
        {
            printf("Too long word");
            continue;
        }
 
        if (*currentWord != '\n')
        {           
            CompareWithSmallest(currentWord, smallestWord);
            CompareWithLargest(currentWord, largestWord);
        }
    } while (*currentWord != '\n');
 
    printf("Smallest word: ");
    WriteWord(smallestWord);
 
    printf("Largest word: ");
    WriteWord(largestWord);
 
    getch();
    return 0;
}
 
int ReadCurrentWord(int *pWord)
{
    char charCounter = 0;
    int counter;
    int ch;
    int *tempPtr = NULL;

    while ((ch = getchar()) != '\n')
        if (++charCounter <= MAX_WORD_LENGTH)
        {
            pWord = (int *)realloc(tempPtr, sizeof(int) * charCounter);
            if (pWord == NULL)
                return ERROR;
            tempPtr = pWord;
            for (counter = 1; counter < charCounter; counter++)
                tempPtr++;
            *tempPtr = ch;
        }
    *++tempPtr = '\0';
 
    return charCounter;
}
 
void CompareWithSmallest(int *pCurrentWord, int *pSmallestWord)
{
    int *pTempCurrent = pCurrentWord;
    int *pTempSmallest = pSmallestWord;
 
    while (*pCurrentWord == *pSmallestWord)
    {
        pCurrentWord++;
        pSmallestWord++;
    }
 
    if (*pSmallestWord > *pCurrentWord)
        while ((*pTempSmallest++ = *pTempCurrent++) != EOF) ;
}
 
void CompareWithLargest(int *pCurrentWord, int *pLargestWord)
{
    int *pTempCurrent = pCurrentWord;
    int *pTempLargest = pLargestWord;
 
    while (*pCurrentWord == *pLargestWord)
    {
        pCurrentWord++;
        pLargestWord++;
    }
 
    if (*pCurrentWord > *pLargestWord)
        while ((*pTempLargest++ = *pTempCurrent++) != EOF) ;
}
 
void WriteWord(int *pWord)
{
    while (*pWord && (*pWord != EOF))
        putchar(*pWord++);
}
Программа предлагает вводить слова, пока не будет введена пустая строка, а затем выводит "самое большое" и "самое маленькое". Если ввести слово длиной более 2-х символов, то программа падает при вызове функции realloc в "ReadCurrentWord", а если вводить слова длиной не более 2-х, то после ввода выводит ошибку доступа чтения, когда идёт обращение к значению указателя currentWord

Решение задачи: «Функция realloc отказывается выделять память»

textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
 
#define MAX_WORD_LENGTH 20
#define SMALLEST_CHAR   0
#define LARGEST_CHAR    255
#define ERROR           -1
 
int ReadCurrentWord(int *pWord);
void WriteWord(int *pWord);
void CompareWithLargest(int *pCurrentWord, int *pLargestWord);
void CompareWithSmallest(int *pCurrentWord, int *pSmallestWord);
 
int main()
{
    int *currentWord = (int *)malloc(sizeof(int));
    int smallestWord[MAX_WORD_LENGTH + 1] = {LARGEST_CHAR};
    int largestWord[MAX_WORD_LENGTH + 1] = {SMALLEST_CHAR};
    int wordLength;
 
    do
    {
        printf("Enter word: ");
 
        if ((wordLength = ReadCurrentWord(currentWord)) == ERROR)
        {
            printf("Error allocation memory");
            return ERROR;
        }
        else if (wordLength > MAX_WORD_LENGTH)
        {
            printf("Too long word");
            continue;
        }
        if (currentWord == NULL)
        {
            printf("NULL");
            getch();
            return 1;
        }
 
        if (*currentWord != EOF)
        {           
            CompareWithSmallest(currentWord, smallestWord);
            CompareWithLargest(currentWord, largestWord);
        }
    } while (wordLength != 0);
 
    printf("Smallest word: ");
    WriteWord(smallestWord);
 
    printf("Largest word: ");
    WriteWord(largestWord);
 
    getch();
    return 0;
}
 
int ReadCurrentWord(int *pWord)
{
    char charCounter = 0;
    int counter;
    int ch;
    int *tempPtr = pWord;
    int *firstPtr = NULL;
 
 
    while ((ch = getchar()) != '\n')
        if (++charCounter <= MAX_WORD_LENGTH)
        {
            tempPtr = (int *)realloc(tempPtr, sizeof(int) * charCounter);
            if (tempPtr == NULL)
                return ERROR;
            firstPtr = tempPtr;
            for (counter = 1; counter < charCounter; counter++)
                tempPtr++;
            *tempPtr = ch;
            tempPtr = firstPtr;
        }
    if (charCounter > 0)
    {
        for (counter = 1; counter < charCounter; counter++)
            tempPtr++;
        *++tempPtr = '\0';
    }
 
    return charCounter;
}
 
void CompareWithSmallest(int *pCurrentWord, int *pSmallestWord)
{
    int *pTempCurrent = pCurrentWord;
    int *pTempSmallest = pSmallestWord;
 
    while (*pCurrentWord == *pSmallestWord)
    {
        pCurrentWord++;
        pSmallestWord++;
    }
 
    if (*pSmallestWord > *pCurrentWord)
        while ((*pTempSmallest++ = *pTempCurrent++) != EOF) ;
}
 
void CompareWithLargest(int *pCurrentWord, int *pLargestWord)
{
    int *pTempCurrent = pCurrentWord;
    int *pTempLargest = pLargestWord;
 
    while (*pCurrentWord == *pLargestWord)
    {
        pCurrentWord++;
        pLargestWord++;
    }
 
    if (*pCurrentWord > *pLargestWord)
        while ((*pTempLargest++ = *pTempCurrent++) != EOF) ;
}
 
void WriteWord(int *pWord)
{
    while (*pWord && (*pWord != EOF))
        putchar(*pWord++);
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

11   голосов , оценка 4.182 из 5
Похожие ответы