Reputation: 11
I am getting a runtime error in this and i can't seem to figure it out. This is my code to reverse a string and change A to T and vice-versa and to change C to G and vice-versa,
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* reverse(char *input)
{
int len=strlen(input);
char *rev=NULL;
rev=(char*)malloc(sizeof(char)*len);
int i,k=0;
for(i=len-1;i>=0;i--)
{
rev[k++]=input[i];
if(rev[k-1]=='A')
rev[k-1]='T';
else if(rev[k-1]=='T')
rev[k-1]='A';
else if(rev[k-1]=='C')
rev[k-1]='G';
else if(rev[k-1]=='G')
rev[k-1]='C';
}
rev[k]='\0';
return rev;
}
int main()
{
char *input=(char *)malloc(sizeof(char)*1000);
scanf("%s",input);
char *str =NULL;//(char*)malloc(sizeof(char)*1000);
str=reverse(input);
printf("%s",input);
free(input);
}
Upvotes: 1
Views: 85
Reputation: 12404
You do not allocate enough memory to hold your reversed string:
int len=strlen(input);
...
rev=(char*)malloc(sizeof(char)*len);
...
rev[k]='\0';
You missed 1 extra byte for the terminating \0
.
And by the way... Please don't cast the return value from malloc
to a pointer.
Upvotes: 4
Reputation: 4104
First of all, you use i++
instead of i--
in the for loop. That means that the for
loop never ends and k
gets very very big and your rev[k]
atempts to access values that it shouldnt.
Secondly, you do not need to allocate memory for str
, because you allocate it in the function.
And you should allocate memory for one more char in the function as you will need if for '\0'
.
Upvotes: 1