0

Please help me find an error in dynamic memory allocation.

It is necessary to print all the words that begin and end with one letter.

The algorithm works with a static array, but there is an error when trying to create a dynamic array.

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

int main()
{
    int len = 0;
    char str[10] = "aba cd geg ";
    char* word = NULL;
    int j = 0;
    int i = 0;
    int n = 0;
    while(str[i]!='\0')
        {
            if(!isspace(str[i]))
            {
                n++;
                word = (char*)realloc(word, (n* sizeof(char)));
                word[j] = str[i];
                j++;
                len++;
            }
            else
            {
                if(word[0] == word[len-1])
                {
                    j = 0;
                    while(j < len)
                    {
                        printf("%c", word[j]);
                        j++;
                    }
                }
                j = 0;
                len = 0;
                free(word);
                n = 0;
            }
            i++;
        }
  return 0;
}

6
  • can i know what is the output you want to get? Commented Mar 13, 2020 at 16:11
  • 1
    You forgit to include #include <ctype.h>. Compile with all warnings enabled and consider them as errors. And char str[10] = "aba cd geg ";, there is not enough space in str you forgot about the NUL string terminator, just use char str[] = "aba cd geg "; and let the compiler figure out the required size. There may be more errors though. Commented Mar 13, 2020 at 16:11
  • OT: for ease of readability and understanding: 1) Please consistently indent the code. Indent AFTER every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces Commented Mar 15, 2020 at 18:49
  • regarding: word = (char*)realloc(word, (n* sizeof(char))); 1) in C, the returned type is void* which can be assigned to any pointer. Casting just clutters the code. Suggest removing that cast. 2) When calling realloc(), always assign to a temp variable. Then check (!=NULL) and if not NULL, then assign to the target variable. Otherwise, the original pointer is lost, resulting in a memory leak. 3) the parameter is expected to be of type size_t, not int, so this statement: int n=0; should be: size_t n=0; Commented Mar 15, 2020 at 18:56
  • when compiling, always enable the warnings, then fix those warnings. ( for gcc, at a minimum use: -Wall -Wextra -Wconversion -pedantic -std=gnu11 ) Note: other compilers use different options to produce the same results Commented Mar 15, 2020 at 18:58

1 Answer 1

1

Once you have freed word, you need to set word to NULL, because realloc can only be performed on a NULL pointer or on a valid pointer that has previously been returned by malloc, calloc or realloc.

  ...
  len = 0;
  free(word);    // after this line, word is no more a valid pointer
  word = NULL;   // <<<< insert this
  n = 0;
  ...

In other words this pattern is always wrong:

 free(foobar);
 foobar = realloc(foobar, ...);

Another possibility is not to free word at all and let the next realloc take care of it, which in this case is most likely more efficient.

  ...
  len = 0;
  // free(word);     remove this line
  n = 0;
  ...

but then you need to call free(word); at the end of the program, just before return 0;

So the end of your program would look like this:

      ...
      j = 0;
      len = 0;
      n = 0;
    }
    i++;
  }

  free(word);
  return 0;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.