Reputation: 363
I am writing Algorithm code for removing similar character. For Ex. If input string is "abb" Output should be "a" and for "abcddbf" string output should be "acf".
I have written some code as mentioned below but some how I am getting Segmentation Faut and I am not able to find the faulty point.
Code :
#include<stdio.h>
#include<string.h>
char *remove_adjecent_string(char *in,int count)
{
int i=0;
int j=0;
int flag = 0;
int total = strlen(in);
static char *output = NULL;
if(count == 0)
{
output=(char *)malloc(sizeof(char)*total);
if(output == NULL)
{
return NULL;
}
for(i=0,j=0;i<=total;i++)
{
if(in[i] != '*')
{
output[j]=in[i];
j++;
}
}
return (char *)output;
}
for(i=0;i<=count;++i)
{
printf("In loop i :%d count :%d \t",i,count);
printf("Before comparition in[i] = %c , in[count] = %c \t",in[i],in[count]);
if(in[i] == in[count])
{
printf("Same found in[%d] = in[%d] = %c",i,count,in[i]);
in[i]='*';
flag = 1;
}
printf(" Next loop i = %d\n",++i);
}
printf("Before Recursion \n");
output =remove_adjecent_string(in,(count-1));
return (char *)output;
}
int main()
{
char *input;
char *output;
int i=0;
input = (char *)malloc(sizeof(char)*10);
if(input == NULL)
{
return;
}
output=(char *)malloc(sizeof(char)*10);
if(output == NULL)
{
return;
}
input = "abbb";
int count = -1;
count=strlen(input);
output=remove_adjecent_string(input,(count-1));
printf("Input String = %s\n",input);
printf("Output String = %s\n",output);
}
Help me to find out the faulty case.
Upvotes: 0
Views: 123
Reputation: 27934
Something I detected is that remove_adjecent_string()
returns a buffer (named output
) containing a string, but between malloc
ing and populating this buffer, at no moment it makes sure its a proper null-terminated string (\0
after the last character). In fact you don't even alloc enought space for that.
Depending on the situation, this may cause your printf()
to print memory garbage and even cause segmentation fault, because it will keep printing whatever is in the memory after your buffer until it finally finds a null byte lost somewhere.
Upvotes: 0
Reputation: 4332
input = "abbb";
so input points to a const string which is not modifiable. it will segv when you try to write to it:
in[i]='*';
add: you seem to want to copy "abbb" to input so consider using strncpy()
Upvotes: 4
Reputation: 2909
How to find segfaults:
-g
-option to the compiler command line.gdb --args ./your-program [args]
for gdb and linux.r
to run the program.bt
to print the call stack. Find the topmost line that is in your code and take the filename and line number.Upvotes: 0