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;
}
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:
'\0'
malloc(x + 1);
sizeof(char)
is always 1 per standardmalloc&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.
Comments