0

I'm trying to make a function which will receive a char * from the user and will print it.

It turns my value to something weird when I'm printing it.

**//input method**

char* readContactName(){
    char tmp[20];
    do{
    printf("What is your contact name?: (max %d chars) ", MAX_LENGH);
    fflush(stdin);
    scanf("%s", &tmp);
    } while (!strcmp(tmp, ""));

    return tmp;
}

void readContact (Contact* contact) 
{

    char* tmp;

    tmp = readContactName();
    updateContactName(contact, tmp);
}

**//when entering this function the string is correct**
void updateContactName(Contact* contact, char str[MAX_LENGH])
{
    printf("contact name is %s\n",&str);  --> prints rubish
}

What did I miss here?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Coder123
  • 784
  • 2
  • 8
  • 29
  • 3
    You cannot return pointers to local variables in C. The compiler lets you do this, but it doesn't work. – fuz Aug 31 '15 at 11:53

1 Answers1

4

In your code, char tmp[20]; is local to the function readContactName(). Once the function finishes execution, there is no existence of tmp. So, the address-of-tmp also becomes invalid.

So, after returning, in the caller, if you try to use the returned pointer, (as you're doing in updateContactName(contact, tmp);()) it will invoke undefined behaviour.

FWIW, fflush(stdin); is also UB. fflush() is only defined for output streams.

Solution:

  • Define tmp as to be a pointer.
  • Allocate memory dynamically (using malloc() or family).
  • Once you're done using the allocated memory, you need to free() it also.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261