'Uninitialized variable' used in this function?

2

After compiling the program, you receive 2 warnings of the same type:

  

"warning: 'phrase is used uninitialized in this function"

and

  

"warning: 'word' is used uninitialized in this function"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *alocar_palavra(char *palavra);
char *alocar_frase(char *frase);

int main(){

  char *frase, *palavra;
  frase = alocar_frase(frase);
  palavra = alocar_palavra(palavra);
  printf("%s", frase);
  printf("%s", palavra);

  return 0;
}

char *alocar_palavra(char *palavra){

  palavra = (char*)malloc(20 * sizeof(char));
  scanf(" %s", palavra);

  return palavra;
}

char *alocar_frase(char *frase){

  char letra;
  int k = 0;
  frase = NULL;

  do{
      letra = getchar();
      frase = (char*)realloc(frase, (k+1)*sizeof(char));
      frase[k] = letra;
      k++;
  }while((letra != '$') && (letra != '\n'));

  return frase;
}
    
asked by anonymous 12.07.2017 / 02:16

1 answer

2

You do not have to pass the variables if you will soon discard their values, when doing this without value causes this problem.

The code can be greatly improved, notice everything I've done. To tell you the truth, these%% variables are not even necessary.

#include<stdio.h>
#include<stdlib.h>

char *alocar_palavra() {
    char *palavra = malloc(20);
    scanf(" %s", palavra);
    return palavra;
}

char *alocar_frase() {
    char letra;
    int k = 0;
    char *frase = NULL;
    do {
        letra = getchar();
        frase = realloc(frase, k + 1);
        frase[k++] = letra;
    } while (letra != '$' && letra != '\n');
    return frase;
}

int main() {
    char *frase = alocar_frase();
    char *palavra = alocar_palavra();
    printf("%s", frase);
    printf("%s", palavra);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
12.07.2017 / 02:47