0

When I try to printf the value, which is a string, it does fine when it is in the push() function but when I run the same command in the main function, it prints garbage. For example if I enter A for the prompt "Enter Value of number: ", I get A printed in the push() but garbage like ?P( from the main function.

struct v
{
    char *value;
    int ibase;
    int obase;
    struct v* next;
};
struct v* top = NULL;

void push(char* val, int ibas, int obas)
{
    struct v* newstackptr=malloc(sizeof(*newstackptr));
    newstackptr->next = top;
    newstackptr->value= val;
    printf("%s",val);//<-prints just fine
    printf("\n%s", newstackptr->value);//<-prints just fine
    newstackptr->ibase= ibas;
    newstackptr->obase= obas;
    top = newstackptr;
    printf("\n%s", top->value);//<-prints just fine
}

void getUserInput(){
    int ibase,obase;
    printf("Enter Value of number: ");
    char value[20];
    scanf("%s",value);
    printf("\nEnter the initial base: ");
    scanf("%d",&ibase);
    printf("\nEnter the output base: ");
    scanf("%d",&obase);
    printf("\n");
    push(value,ibase,obase);
}
char* getValue(){
    return top->value;
}
int main(){
    getUserInput();
    printf("%s",top->value);//<-this returns garbage
    printf("%s",getValue());//<-this returns garbage
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
akira kato
  • 21
  • 1
  • 5
  • 5
    `top->value` is on `getUserInput()`'s stack - you need to allocate memory for it... try using `strdup()`. Also, watch out because `scanf()` is not safe... try entering 40 characters. – Attie Feb 20 '18 at 21:21
  • The `value` variable is only valid when `getUserInput` hasn't returned. Once this function returns, `top->value` points to an invalid location. Change your struct to have an array, `char value[20];` and the use `strncpy(newstackptr->value, val, sizeof newstackptr->value); newstackptr->value[sizeof(newstackptr->value) - 1] = 0;` instead. – Pablo Feb 20 '18 at 21:25
  • @Pablo So replace char *value; with char value[20]; and replace the inside of push() with struct v* newstackptr=malloc(sizeof(*newstackptr)); newstackptr->next = top; strncpy(newstackptr->value, val, sizeof newstackptr->value); newstackptr->value[sizeof(newstackptr->value) - 1] = 0; newstackptr->ibase= ibas; newstackptr->obase= obas; top = newstackptr; – akira kato Feb 20 '18 at 22:02
  • Sorry, the comment section is not meant for to much code without backticks, edit your question and post that in the question. – Pablo Feb 20 '18 at 23:20

0 Answers0