Reputation: 59
Please consider the below code.
#include<stdio.h>
#include<string.h>
void main()
{
char a[6], b[6];
strcpy(a,"rajeev");
printf("print A:");
for(int i=0;i<strlen(a);i++)
{
printf("%c",a[i]);
}
strcpy(b,a);
printf("print B:");
for(int i=0;i<strlen(b);i++)
{
printf("%c",b[i]);
}
printf("trying to print A again");
for(int i=0;i<strlen(a);i++)
{
printf("%c",a[i]);
}
While running this program,in the "trying to print A again" section prints nothing, and the strlen(a)
will be 0. That means the source array will be empty.
Can you please help me to understand the phenomena behind this?
But, change the declaration of a[6]
to char* a=malloc(6)
works properly.
Upvotes: 0
Views: 9156
Reputation: 493
The array you defined char a[6], b[6]
don't have enough space to fit the string you are trying to store.
Kindly remember that every array in C has a null byte \0
at the end.
You can fix it by giving enough space to the array:
char a[7], b[7];
Upvotes: 1
Reputation: 67516
a & b are too small and because a is just after b the first byte of it is zero after the strcpy execution.
malloc has worked because this chunk of memory was allocated in the other place in the memory. But it was just accidental, as you wrote more memory than you have allocated.
Any access to the memory which was not somehow allocated is illegal and it is an UB.
Upvotes: 0
Reputation: 310980
The string literal "rajeev"
has type char[7]. That is it has the static storage duration and is stored as an array initialized like
char unnamed[] = { 'r', 'a', 'j', 'e', 'e', 'v', '\0' };
So if you are going to copy its content as a string using the function strcpy
you need provide enough memory in the destination array. For example
char a[7], b[7];
strcpy(a,"rajeev");
printf("print A:");
for ( size_t i = 0, n = strlen( a ); i < n; i++ )
{
printf("%c",a[i]);
}
//... and so on
Take into account that the function strlen
counts characters until the terminating zero is encountered. So if a character array does not include this character then the function's behavior is undefined.
Upvotes: 5
Reputation: 223907
Your arrays aren't being enough to hold the string you're trying to store.
String in C are defined as a null terminated sequence of characters, meaning that a proper string has a null byte at the end.
Your arrays can hold 6 bytes, but your string "rajeev"
needs 7 bytes (6 for the letters and one for the implicit null byte at the end. As a result, you write past the end of the array. Writing outside the bounds of an array invokes undefined behavior.
In the case where you dynamically allocate memory, you are again invoking undefined behavior. In this case it appears to work properly. That's one of the ways undefined behavior can manifest.
To fix this, your arrays need to be at least 7 elements long:
char a[7], b[7];
Upvotes: 2