Hi, i'm facing a weird behavior in this code that i just wrote. It was supposed to read a string from stdin and just write it out.
I've debugged it and for me it reads perfectly, but in the while (line 38), *p just seems to be taking weird chars although it's pointing to the correct mem address (checked with those printf i put).
What's going on?

#include <stdio.h>
#define LONG 100

char * leer();
void printar(char *);

int main()
{
    printf("Insert a string: ");
    //char *str = leer();
    printar(leer());
    return 0;
}

char * leer()
{
    char str[LONG], *p;
    int c;
    p = str;

    while((c = getchar()) != EOF)
    {
        if(c == '\n')
        {
            *p = 0;
            break;
        }
        *p = c;
        printf("p = %p, *p = c = %c\n", p, *p);
        p++;
    }
    return str;
}

void printar(char *str)
{
    char *p = str;
    while(*p != 0)
    {
        printf("p = %p, *p = %c\n", p, *p);
        putchar(*p);
        p++;
    }

}

This function returns the address of the local variable str

char * leer()
{
    char str[LONG], *p;
    int c;
    p = str;

    while((c = getchar()) != EOF)
    {
        if(c == '\n')
        {
            *p = 0;
            break;
        }
        *p = c;
        printf("p = %p, *p = c = %c\n", p, *p);
        p++;
    }
    return str;
}

This function returns the address of the local variable str

Variable str is created when the function leer() is used. It is [1]destroyed when the function leer() is finished. You are returning a pointer to that memory that might or might not contain the previous declared value.

[1] nothing is destroyed, it is just released as part of leer() and now it is available to reuse.

This function returns the address of the local variable str

Variable str is created when the function leer() is used. It is [1]destroyed when the function leer() is finished. You are returning a pointer to that memory that might or might not contain the previous declared value.

[1] nothing is destroyed, it is just released as part of leer() and now it is available to reuse.

Oook!! Now that makes a lot of sense, thank you. That's why it only printed the first char. Grrr i should have known.

Mental note: next time give more credit to debug's warnings.

This function returns the address of the local variable str


Oook!! Now that makes a lot of sense, thank you. That's why it only printed the first char. Grrr i should have known.

Mental note: next time give more credit to debug's warnings.

I'm not sure which compiler your using but you should engage your warnings...i.e. gcc has a switch setting -Wall which is "warn all" and it picked up this problem in the compile stage..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.