Search code examples
cstringloopsconcatenation

Why the program crashes when I am trying to use strcat() in for-loop?


I have an issue with strcat. When I am trying to use it in for-loop it throws a reading access violation. There is a program as example:

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

printf("Enter count: ");
int count = 0;
scanf("%d", &count);
char* str = (char*)malloc(sizeof(char));
for(int i = 0; i < count; i++) str = strcat(str, "a");

It works fine with values in kind of 10 or 100 for count but it crashes when I use it with 1000 or bigger. Can someone tell me what's the problem?


Solution

  • Your code has several problems:

    1. you only allocate space for one character
    2. you never initialize the string before calling strcat
    3. you forgot to include <stdlib.h>

    You want this:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>         // you need this for malloc
    
    int main()
    {
      printf("Enter count: ");
      int count = 0;
      scanf("%d", &count);
    
      char* str = malloc(sizeof(char) * (count + 1));  // allocate count + 1 bytes, the +1 
                                                       // is for the string NUL terminator
    
      str[0] = 0;                    // initialize the string to an empty string
    
      for (int i = 0; i < count; i++)
        str = strcat(str, "a");
    
      printf("Result = %s\n", str);  // print the result
    }
    

    BTW the (char*) cast is not needed with malloc.