mario razzu
mario razzu

Reputation: 383

Issue with string creation C

I want to make a function that create a new string with a specific lenght. This is the code:

char* newString(int lenght){

    char* newstring =(char*)((calloc(lenght, sizeof(char))));
    newstring[lenght] = '\0';
    return newstring;
}

I use it in this way:

char* string = newString(10);

My problem is that when I do:

printf("String lenght  %lu \n",strlen(string));

I get 0 but I don't understand why. I am neophyte with C. Thank for your time

Upvotes: 1

Views: 59

Answers (4)

Narcisse Doudieu Siewe
Narcisse Doudieu Siewe

Reputation: 649

strlen count the number of character in the c string until it see a "\0" (end of string) so as your string is initialized with "\0" its length is actually 0. change this value to another one like.

  memcpy(string, "good things", 10);
  printf("%d", strlen(string));

Upvotes: 0

TJ1S
TJ1S

Reputation: 528

There's a couple of issues here. The first is that you're terminating t (and I'm not sure what t references actually) with a null-terminator at index "length", which will be one greater than the size of the array. So you're accessing some random blob of memory there. The second is improperly using calloc. I think you want something more like:

char* new_string(int length) {
    char* new_string;
    new_string = malloc(sizeof(char) * length);
    memset(new_string, 0, length);
    new_string[length-1] = '\0';
    return new_string;
}

Strlen in your example returns 0 because it counts the characters before the null terminator, which happens to be 0 in your implementation.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

strlen returns the number of characters before the first '\0'. You'll get the same result if you use:

char s[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int len = strlen(s); // len will be zero.

Upvotes: 4

Ron Kuper
Ron Kuper

Reputation: 847

If length doesn't include the null termination then you should set t[length - 1] to zero, or alternatively calloc with size length + 1.

Upvotes: 0

Related Questions