1

I have a function that finds Roman numerals of numbers passed in an array and stores them in a string array and returns the string array to the main(). But when I try to access the returned string array in main(), the code fails due to segmentation fault. Can someone please explain me why this is happening and how can i correct my code?

Added comments in the code where segmentation fault is seen and where it works fine. Thanks alot for your time and help.

int find_lookup_index(int temp)
{

    int j=0;
    while(1)
        {
            if(temp>=lookup_int[j] && temp<lookup_int[j+1])
                break;
            j++;
        }
    return j;
}

char** romanizer(int num_size, int* num)
{

    int i,j,temp;
    char result[num_size][20];


    for(i=0;i<num_size;i++)
    {
        strcpy(result[i],"\0");

        if(num[i]%1000 == 0)
        {
            strcpy(result[i],"M");
            continue;
        }

        j=find_lookup_index(num[i]);

        temp=num[i];
        while(temp>0)
        {
            strcpy(result[i],strcat(result[i],lookup_char[j]) );
            temp = temp - lookup_int[j];
            j = find_lookup_index(temp);
        }        

    }

    **/* WORKS CORRECTLY HERE */**
    for(i=0;i<num_size;i++)
        printf("%s\n",result[i]);
    return (char **)result;
}

int main() 
{

    int size,i;
    char **result;

    int arr[3] = {3,11,499};
    result = romanizer(3,arr);

    **/* NOT WORKING - SEGMENTATION FAULT - WHY ? */**
    for(i=0;i<3;i++)
        printf("%s\n",result[i]);

    return 0;
}
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • 1
    possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Retired Ninja Jun 07 '15 at 06:50
  • 2
    Not only are you returning a local automatic var by-address, it isn't of the type you're casting regardless. a `char[n][m]` does *not* express as `char**`, and that it wouldn't compile without that hard-cast should be a hint to that. May as well fix both problems at the same time. – WhozCraig Jun 07 '15 at 06:52

2 Answers2

3

result is defined on the stack, and is "free"'d off the stack when romanizer is finished executing. So when your main tries to use it, it gets a segmentation fault.

The solution is to malloc the data structure (which allocates it on the heap rather than the stack), and have the caller free it when it's no longer needed.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Tushar
  • 8,019
  • 31
  • 38
1

Inside your romanizer function, you are allocating result on the stack, which is freed automatically for you upon return from your function. When you try to use it in main it is already gone.

You must either allocate it on the heap with a new/Malloc and then delete/free it in main, or allocate it in main and pass it in as a parameter instead of a return value.

Scott 'scm6079'
  • 1,517
  • 13
  • 25