Reputation:
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?
Upvotes: 0
Views: 190
Reputation: 50831
Your code has several problems:
strcat
<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
.
Upvotes: 3
Reputation: 27
It seems str
is not initialized, moreover you are allocating sizeof(char)
so the size of str
is only one char.
The function strcat
concatenates 2 string, str
and "a" but a string must be terminated by '\0'. So in strcat
reach the end of string and reads in not allocated memory.
Upvotes: 1