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

char* foo (const char* str)
{
    char szo[125];
    char* vege;
        int i,j=0;
        int db=1;
        szo[0] = str[0];
        for(i=1; i<strlen(str)+1; i++)
        {
            if(str[i] == str[i-1] )
            {
                    db++;
            }
            else
            {
                j++;
                szo[j] = db + '0';
                j++;
                szo[j] = str[i];
                db=1;
            }
        }
        j++;
        szo[j] = '\0';
        vege = szo;
    return vege;
}

int main()
{
    char *s[] = {"hello", "world", "Mississippi"};
    int i;
    for (i = 0; i < sizeof(s) / sizeof(char *); ++i)
    {
        char *p = foo(s[i]);
        printf("%s\n", p);
    }
    return EXIT_SUCCESS;
}

I've tried to do first a printf("\n"), then its good, but i have a empty first line. Someone can please help me.Thanks a lot. Or if anyone can help me, the original tasks say a free(p) in the main after the printf, how can i change everything to work with malloc?

Sliwd
  • 13
  • 3
  • foo is returning a pointer to local memory which is gone after the return. – stark Jan 02 '20 at 14:03
  • `foo` is returning the address of a local variable on the stack, which you then proceed to use in `main` resulting in Undefined Behavior. – Jonathon Reinhart Jan 02 '20 at 14:04
  • Does this answer your question? [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Sander De Dycker Jan 02 '20 at 14:11
  • OT: for ease of readability and understanding: Please consistently indent the code. Do not mix tabs and spaces when indenting – user3629249 Jan 03 '20 at 16:13

2 Answers2

1

szo ceases to exist right before foo() returns.
Yet you return a pointer to that array and try to use it outside the function.

If you're not ever going to call foo recursively, or in parallel in several threads, or as different arguments of another function, try static char szo[125]; and remember to document that the function returns a pointer to a static array so that you don't invoke UB in 6 months time

char *foo(const char *str) {
    static char szo[125];
    //...
    return szo;
}

printf("%s\n", foo("something")); //ok
printf("%s\n", foo("some other thing")); //ok
//printf("%s\n%s\n", foo("something"), foo("some other thing")); //NO
pmg
  • 106,608
  • 13
  • 126
  • 198
0
char* foo (const char* str)
{
    char szo[125];    
    ...
    vege = szo;
    return vege;
}

you return pointer to the local variable which does not exist after the return from the function. One of the most common UBs

0___________
  • 60,014
  • 4
  • 34
  • 74