Abderrelmsd
Abderrelmsd

Reputation: 13

array contents duplicate in C?

I wrote a simple program to check if the method of declaring a string affects if a string terminator is added by default or not, however, I noticed that the contents of one array are copied to another. Why is this happening?

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

int main() {
    char *Name1 = "Name1";
    char Name2[] = "Name2";
    char Name3[] = {'N','a','m','e','3'};
    printf("Name1 = %lu\n",strlen(Name1));
    printf("%s\n",Name1);
    printf("Name2 = %lu\n",strlen(Name2));
    printf("%s\n",Name2);
    printf("Name3 = %lu\n",strlen(Name3));
    printf("%s\n",Name3);
    return 0;
}
# Name1 outputs 5 -> Name1
# Name2 outputs 5 -> Name2
# Name3 outputs 10 -> Name3Name2

Upvotes: 1

Views: 47

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You invoked undefined behavior by:

  • Passing data having wrong type to printf(): strlen() returns size_t and correct format specifyer to print that is %zu.
  • Passed character sequence that is not null-terminated (Name3) to functions that expects strings (character sequence terminated by null-character).

It seems that Name2 is happened to be allocated next to Name3 and therefore readings from string-expecting functions slipped there.

Upvotes: 2

Related Questions