How did Char array accepts letters more than it's initialized size

63 Views Asked by At

I want to concatenate two char array in C. I found this code somewhere. I know that the array size once it has been initialized, it can't be resized. the alternative way to implement dynamic array of characters is to use Dynamic Memory Allocation. but in the code below in the you can find we have a char array called 'first' with size of 8 bytes including "\0" then we pass the 'first' array to the concatenateStrings function now the size of 'dest' array should be 8 bytes. in this function you can find the 'src' array of size 7 bytes is concatenated to 'dest' array. The 'dest' array size should be 8 bytes my question is how did the 'dest' array accept more characters. because by the end of the concatenation process you can find that 'dest' array contains 13 characters. also should the size of array be equal to number of letters in the array because one character = 1 bytes. so when i execute this program i got the sizeof(dest) is 8 and strlen(dest) is 13

            #include <stdio.h>
            #include <stdlib.h>
            void concatenateStrings(char dest[], const char src[]) {
            /* Find the end of the destination string (null terminator) */
            int i = 0;
            while (dest[i] != '\0') {
                i++;
            }
        
           /* Copy characters from src to the end of dest */
           int j = 0;
           while (src[j] != '\0') {
               dest[i++] = src[j++];
           }
        
           /* Add null terminator to the concatenated string */
           dest[i] = '\0';
           printf("dest string: %d\n", sizeof(dest));
           printf("dest len string: %d\n", strlen(dest));
           printf("src string: %d\n", sizeof(src));
        }
        
        int main() {
           char first[] = "Hello, ";
           char second[] = "World!";
        
           printf("First string: %d\n", sizeof(first));
           printf("Second string: %d\n", sizeof(second));
        
           concatenateStrings(first, second);
        
           printf("Concatenated string: %s\n", first);
        
           return 0;
        }
1

There are 1 best solutions below

5
dbush On BEST ANSWER

C doesn't perform any kind of bounds checking on arrays. That's part of what makes it fast. However, that also means that if you read or write past the end of your array, this invokes undefined behavior.

With undefined behavior, the C standard makes no guarantee what your program will do. It might crash, it might output strange results, or it could appear to work properly. Worse, how undefined behavior manifests can change with seemingly unrelated changes to your code, such as adding a printf statement for debugging or adding an unused local variable.

So you need to change your code to not do that, as the language expects that you'll do the right thing.