This is a simple code that i’ve written because i need a confirmation about a thing.
#include <stdio.h>
#include <string.h>
void pr(int a);
int main(void)
{
int a;
printf("starting...\n");
h1:
scanf("%d", &a);
if (a == 20)
return 0;
pr(a);
goto h1;
printf("ending...\n");
return 0;
}
void pr(int a)
{
char buf[256];
if (a == 1)
strcpy(buf, "number 1 has been choosed");
else
strcpy(buf, "other number");
printf("BUF: %s\n", buf);
}
My question is:
Every time the function pr is called, the array buf is automatically cleared or it is more secure to do a memset before the function end?
No, it will contain undefined data since it has automatic storage. The simplest would be to:
Or, since you’re using
bufas a string, you could go with the cheaper:Side note: the way your code looks you don’t need this initialization since
strcpydoesn’t depend on it and you have astrcpyon each branch.