This is my code:
char *genWord(int wordLen){
char array[wordLen + 1];
char *word;
int i;
for(i = 0; i <= wordLen; i++){
array[i] = 'a';
}
array[wordLen] = '\0';
//Test1 printf
printf("%s \n", array);
word = array;
//Test 2
printf("%s \n", word);
return word;
}
main(){
char *word;
int wordLen = 10;
word = (char *)genWord(wordLen);
//Test 3
printf("%s", word);
}
And this is my output of 3 (same prog) executes in Linux gcc:
1st:
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaT��aaaaa
2nd:
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaa�ƃ�aaaaa
3rd:
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaa����aaaaa
Can’t figure out what’s wrong and even worse, can’t imagine how can i get a different output on every run? variable word can’t have garbage in a part of the string right?!
You are returning local address, which is not anymore guaranteed to be allocated after the return from call. Therefore it is an undefined behaviour.
When you do
word = arraythe local address of the array is copied intowordvariable. After return the calling function has the address, which was the local address in the function. But after the function return the address is not anymore valid, and may be allocated for other purpose, or overwritten or anything.Do
word = strdup (array);OR