-1

If needed , you might run the example code below here:

Online C compiler

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

void foo(char *name);
char bar(char c);
 

int main(int argc, char **argv)
{
    foo("Ashcroft");
    return 0;
}

void foo(char *name)
{
    printf("name = %s\n", name);
    int name_length = strlen(name);
    char code[name_length];
    printf("length of name %d\n", name_length);

    for (int i = 0; i < name_length; i++)
    {
        code[i] = bar(name[i]);
    }
    printf("length of code is %ld\n", strlen(code));

    printf("name is %s\n", name);
}

char bar(char c)
{
    return 'a';
}

Problem

I expected length of code to be the same as length of name, but somehow the length changes after the for loop.

Output

name = Ashcroft
length of name 8
length of code is 14
name is Ashcroft

Update tried char code[name_length+1]; but the result is still the same

result

David
  • 373
  • 3
  • 21

1 Answers1

2

You declared code to be just long enough to hold the characters that are part of the string in name, but not enough to hold the terminating null byte that strings end with.

So when you pass code to strlen and printf, they read past the end of the array looking for the terminating null byte. Reading off the end of an array triggers undefined behavior which in this case manifests as an unexpected length for the string.

You need to make code one element longer to hold the terminating null byte:

char code[name_length+1];

And also add the null byte after building the string:

int i;
for (i = 0; i < name_length; i++)
{
    code[i] = bar(name[i]);
}
code[i] = 0;
dbush
  • 205,898
  • 23
  • 218
  • 273