473,320 Members | 1,991 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Seg-fault in recursion

Sorry if this appears twice.
Input : Hello I am a newbie
Output: newbie a am I Hello

I am getting a segfault on running the progra.The debugger shows that it
happens in the reverse routine
Can anyone help me fix it ?

#include <stdio.h>
#include<string.h>
#include <stdlib.h>
void reverse(char **);
void print_2_array(char** array1 ,int row,int col);

void reverse(char **words)
{
if(*(words + 1) != '\0')
{
reverse((words + 1));
}
printf("%s",*(words + 0));
}
void print_2_array(char** array1 ,int row,int col)
{
int i, j;

for (i=0; i < row; i++)
{
for(j=0; j < col; j++)
printf("%c", array1[i][j]);
printf("\n");
}
}

int main() {
char line[200];
char **words;
int i = 0,j = 0,k = 0;
char* a =line;

words = (char**)malloc(10*sizeof(char*));
words[j] = (char*)malloc(15*sizeof(char));

memset(words[j],0,15*sizeof(char));

scanf("%[^\n]s",line);

for(; *a ;i++)
{
if(*a == ' ')
{
j++;
words[j] = (char*)malloc(15*sizeof(char));
memset(words[j],0,15*sizeof(char));
*(*(words + j) + k) = '\0';
k = 0;
}
*(*(words + j) + k) = *a;
k++;
a++;
}
*(*(words + j ) +k) = '\0';
print_2_array(words,j+1,15);
reverse(words);
}
Jul 9 '08 #1
5 1476
"Newbie" <ne****@gmail.comwrote in message news:g5**********@aioe.org...
Sorry if this appears twice.
Input : Hello I am a newbie
Output: newbie a am I Hello

I am getting a segfault on running the progra.The debugger shows that it
happens in the reverse routine
Can anyone help me fix it ?
words = (char**)malloc(10*sizeof(char*));
Try inserting here:

memset(words,0,10*sizeof(char*));

However there lots of other issues with this program. For one thing mixing
a[i] notation with *(a+i) which makes it hard to follow.

Try using proper diagnostic printing such as this, before any output
routines; then you will know exactly what is in words:

for (i=0; i<10; ++i) {
printf("Words[%d] = %x",i,words[i]);
if (words[i]) printf(": \"%s\"",words[i]);
printf("\n");
}

Also the constants 10 and 15 should be defined somewhere. The malloc values
should be checked against NULL.

For rapid testing, forget the scanf and just use something like strcpy(line,
"ABC DEF");

--
bartc
Jul 9 '08 #2
Newbie <ne****@gmail.comwrites:
Input : Hello I am a newbie Output: newbie a am I Hello

I am getting a segfault on running the progra.The debugger shows that
it happens in the reverse routine
Can anyone help me fix it ?
To remove the problem you are seeing, you need to make sure that the
condition you test for in 'reverse' will eventually be met. In other
words the array of pointers must end with a pointer that compares
equal to '\0'[1]. That needs one line at the end of the for loop in
main.

To make it better, you could:

- Remove the "magic numbers" (replace then with #defines).
- Set and test pointers against NULL rather than '\0'.
- Use p[i] syntax rather than *(p + i).
- Stop long lines from overflowing your input buffer.
- Stop lines with lost of words overflowing your pointer array.
- Stop long words in a line overflowing your word arrays.
- Do it without recursion.
- Print the input without all the null characters.
- Print the input using printf rather than with your own function.
- Use a simpler data structure (maybe just an array of pointers?).
- Use a simpler algorithm (reverse the words in place, maybe?).

[1] I mean that, but see my second improvement.

--
Ben.
Jul 9 '08 #3
Ben Bacarisse wrote:
Newbie <ne****@gmail.comwrites:
>Input : Hello I am a newbie Output: newbie a am I Hello

I am getting a segfault on running the progra.The debugger shows that
it happens in the reverse routine
Can anyone help me fix it ?

To remove the problem you are seeing, you need to make sure that the
condition you test for in 'reverse' will eventually be met. In other
words the array of pointers must end with a pointer that compares
equal to '\0'[1]. That needs one line at the end of the for loop in
main.

To make it better, you could:

- Remove the "magic numbers" (replace then with #defines).
- Set and test pointers against NULL rather than '\0'.
- Use p[i] syntax rather than *(p + i).
- Stop long lines from overflowing your input buffer.
- Stop lines with lost of words overflowing your pointer array.
- Stop long words in a line overflowing your word arrays.
- Do it without recursion.
- Print the input without all the null characters.
- Print the input using printf rather than with your own function.
- Use a simpler data structure (maybe just an array of pointers?).
- Use a simpler algorithm (reverse the words in place, maybe?).

[1] I mean that, but see my second improvement.
I did not write the code.It looked like a mess initially (far worse) .My
friend asked me to debug it :(

This is my solution :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50

void reverse(char* begin, char* end)
{
char tmp;
while(begin<end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
++begin;
--end;
}
return ;
}
char *reverse_words(char *str1)
{
unsigned int i;
char *token;
reverse(str1,str1+strlen(str1)-1);

token=strtok(str1," ");
while(token != NULL)
{
reverse(token,token+strlen(token)-1);
for(i=0;i<strlen(token)-1;token++);
*++token=' ';
token = strtok(NULL, " ");
}
return str1;
}
int main(void)
{
char str1[MAX];
printf("Enter the string to be reversed word by word\n");

if(fgets(str1,MAX,stdin)!=NULL)
{
str1[strlen(str1)-1]='\0';
printf("Original String :%s\n",str1);
printf("Reversed String :%s\n",reverse_words(str1));
}
else
printf("Null String entered");
return 0;
}

Jul 9 '08 #4
Ben Bacarisse wrote:
Newbie <ne****@gmail.comwrites:
>Input : Hello I am a newbie Output: newbie a am I Hello
..snip..
To make it better, you could:

- Remove the "magic numbers" (replace then with #defines).
- Set and test pointers against NULL rather than '\0'.
- Use p[i] syntax rather than *(p + i).
- Stop long lines from overflowing your input buffer.
- Stop lines with lost of words overflowing your pointer array.
- Stop long words in a line overflowing your word arrays.
- Do it without recursion.
- Print the input without all the null characters.
- Print the input using printf rather than with your own function.
- Use a simpler data structure (maybe just an array of pointers?).
- Use a simpler algorithm (reverse the words in place, maybe?).

[1] I mean that, but see my second improvement.
Fixed it ! Thanks
Jul 9 '08 #5
On Wed, 09 Jul 2008 22:40:20 +0530, Newbie <ne****@gmail.comwrote:

snip
>I did not write the code.It looked like a mess initially (far worse) .My
friend asked me to debug it :(

This is my solution :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50

void reverse(char* begin, char* end)
{
char tmp;
while(begin<end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
++begin;
--end;
}
return ;
}
char *reverse_words(char *str1)
{
unsigned int i;
char *token;
reverse(str1,str1+strlen(str1)-1);

token=strtok(str1," ");
while(token != NULL)
{
reverse(token,token+strlen(token)-1);
for(i=0;i<strlen(token)-1;token++);
*++token=' ';
These last two lines are an expensive way of saying
*(token+strlen(token)) = ' ';
or the equivalent
token[strlen(token)] = ' ';
which would call strlen exactly once instead of n times depending on
the length of the current word.
token = strtok(NULL, " ");
}
return str1;
}
int main(void)
{
char str1[MAX];
printf("Enter the string to be reversed word by word\n");

if(fgets(str1,MAX,stdin)!=NULL)
{
str1[strlen(str1)-1]='\0';
printf("Original String :%s\n",str1);
printf("Reversed String :%s\n",reverse_words(str1));
}
else
printf("Null String entered");
This error message is incorrect. If the user presses ENTER in
response to the prompt, fgets will store a '\n' followed by a '\0' in
str1 and return the address of str1[0].

If fgets did return a NULL, it means either an error occurred
obtaining the data or end of file was encountered before reading the
(MAX-1)th character.
return 0;
}

Remove del for email
Jul 10 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Michael | last post by:
Trying to process xml (xml-rpx) with a handler in mod_python crashes mod_python. Previous versions worked fine. Only change is I recompiled with newest versions of Apache, Python, and mod_python....
4
by: hpy_awad | last post by:
What are the reasons of that message ? linker error fixup overflow at 'seg:xxxx' h,target = 'symbol' in module 'module' I am just compiling a small program under Borland C++ ver 3. #include...
7
by: Berk Birand | last post by:
Hi, For an assignement that I have, I have to write a function that is used for duplicating arrays of some objects (called Product). It is supposed to be something similar to strndup, but taking...
4
by: stephenma7 | last post by:
Hi, everybody. I am new here. I have encountered these many problems for the last couple of days. I have Linux Fedora Core 3(Gnu G++ 3.4.2), Linux Fedora Core 2 (Gnu G++ 3.3.3), Red Hat 9 (Gnu...
4
by: a2x | last post by:
Hi, I've fixed this error, but I don't know why it occurs. Do you? Code: #include <stdlib.h> #include <string.h> void another(); int main()
11
by: grid | last post by:
Hi, Many times I have observed that some program which functions properly without optimisation or with debug option dosn't seem to work when optimasation is on or at a higer level.And occasionally...
4
by: whocares | last post by:
hi everyone. i'm currently experiencing a strange problem under vc++ 2005 express. i hope someone has a hint for me, i'm kind of lost atm. i'm using a vectors of pointers in my code. using...
5
by: Philippe C. Martin | last post by:
Hi, I just installed (compiled) Python 2.4.2 under Suse 10. The following code generates a seg error: import shelve print shelve.open ('test') I assume this has to do with the db behind...
13
by: ralphedge | last post by:
These sorts work fine on 100000 ints but if I go much higher they will both segmentation fault **************************MERGESORT********************* mergesort(int *a, int size) //a is...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.