Pointer function returning false value

superHero

I have written a function like this, when the parameter x is even it doesn't work as desired, for example if I type printf("%s",maxCharac(2)) in main it will print aa and an extra character next to it, but with an odd number it works properly.

char *maxCharac(int x)
{
    char *str=(char*)malloc(sizeof(char)*x);
    for(int i=0;i<x;i++)
    {            
        str[i]='a';
    }
    return str;   
}
LPs

C strings are NUL terminated, so

char *maxCharac(int x)
{
    char *str = malloc(x + 1);

    if (str != NULL)
    {
       for (int i = 0; i < x; i++)
       {
          str[i] = 'a';
       }
       str[i] = '\0';
    }

    return str;
}

As you can see:

  1. You must leave room for a null terminator '\0' malloc(x + 1);
  2. sizeof(char) is always 1 per standard
  3. You must check malloc&co return value != NULL before use it.

Or, to avoid last instruction you can use calloc that zeros the allocated memory

char *maxCharac(int x)
{
    char *str = calloc(x + 1, 1);

    if (str != NULL)
    {
       for (int i = 0; i < x; i++)
       {
          str[i] = 'a';
       }
    }

    return str;
}

Last thing, as per function, the caller must check return value of function to ensure to not use the possible NULL pointer returned:

int main(void)
{
    char *str = maxCharac(2);

    if (str != NULL)
    {
        printf("Test: %s\n", str);
    }   
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related