Reputation: 21
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;
}
Upvotes: 1
Views: 630
Reputation: 8049
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.
Upvotes: 3
Reputation: 1567
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.
Upvotes: 1