Uninitialized variable used in this function?

Asked

Viewed 569 times

3

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;
}
  • realloc can only be called after malloc, calloc, or realloc as indicated in the documentation, otherwise you can get undetermined results

1 answer

4


There is no reason to pass the variables if soon after you will discard their values, when you are doing it without value cause this problem.

The code can be greatly improved, understand everything I’ve done. To tell you the truth, these variables main() nor are they 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.