Implementing strcat using pointers - c

While doing some programs on strings, I have come across this little problem.
The question which was asked to me was this -
Write a pointer version of the function strcat(s,t) which copies the string t to the end of s.
I wrote the program as this -
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char *s1, *s2;
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
I know i have done something(or many things) terribly wrong. Because whenever i try to run this code- it gives me segmentation fault. Like this-
Enter the first string
Hello
Enter the second string
Segmentation fault (core dumped)
It would be really helpful if someone points me out the flaw/flaws of my implementation. Thanks in advance.
Thank you very much guys, for such quick responses. But seems that wasn't the only problem. After writing the program like this-
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char s1[20], s2[20];
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
It runs like this.
Enter the first string
Hello
Enter the second string
There
Hello
It only prints the first string i have entered. Now i think i have made some mistake on that strcat function too.

1) In the main(), you have to allocate memory for both s1 and s2 pointers
char *s1=malloc(100*sizeof(char)), *s2=malloc(100*sizeof(char));
scanf("%99s",s1); //the "%99s" allow to avoid buffer overflow
And if you use gcc and your gcc>2.7 then you can use "%ms" in the scanf() in this way:
scanf("%ms",&s1);
with the "%ms", the scanf() will allocate memory for s1 pointer
2) and you have to add s-- in
while(*s++)
;
s--; // add s-- here
while(*s++ = *t++)
;
because the s pointer is pointing in the next element of '\0' element. the s pointer should be pointed in the '\0' element before starting copy the second string

You don't allocate memory for s1, s1 (or initialized with array), Value of both s1, s1 are garbage .
char *s1, *s2;
printf("enter the first string\n");
scanf("%s",s1);
This causes an undefined behavior.
Suggestion use either:
#define SIZE 1024
char s1[SIZE], s2[SIZE];
or dynamically allocate memory using calloc()/maloc() functions:
char *s1, *s2;
s1 = malloc(SIZE);
s2 = malloc(SIZE);
and lately free() memory explicitly when work done with s1, s2.
Additionally instead of unsafe scanf() use fgets() function to avoid buffer overflow error. read Reading a line using scanf() not good?

Related

Stack smashing detected when trying to copy one string to another using pointers

I am trying to copy one string to another using pointers, but stack smashing error occurred, while the string is copied successfully.
Here's the code below,
#include <stdio.h>
void strcat(char *str1, char *str2) {
char *run = str1;
while(*run !='\0')
run++;
while(*str2 !='\0') {
*run = *str2;
run++;
str2++;
}
*run = '\0';
}
int main() {
char s[] = "hellomojo";
char t[] = "world";
printf("\ns :%s", s);
printf("\n t :%s",t);
strcat(s, t);
printf("\ns after:%s",s);
}
Is it due to illegal access to memory not pointed by pointers?
This char s[]="hellomojo"; is basically the same as char s[10]="hellomojo";. It is an array of 10 characters (including the NUL-terminator). You cannot store more than 10 characters in it. But you concatenate the other string with this, writing into illegal memory locations beyond the array. This invokes Undefined Behaviour. Hence the stack smashing problem.
The fix would be to increase the size of the first array like:
char s[32] = "hellomojo"; /* 32 chosen arbitrary */
Working with what little code was supplied, my guess would be that at least one of those char pointers doesn't have enough allocated memory, or does not have a null terminating character as expected.
You show the code, but what is the output and the error message? With more information, it would be easier to debug.

I'm getting Runtime Error : Segmentation Fault (SIGSEGV), why?

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);
}
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.
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'.

Search my name in statement ! in c program using string functions

I need to know whats wrong with this code.
#include<stdio.h>
#include<string.h>
int main() {
char a[50], b[100], c[5000];
char *ret;
//enter first name
gets(a);
//enter secend name
gets(b);
//enter statement
gets(c);
strcat(a,b);
if(strstr(c,a) != NULL) {
printf("found your full name");
} else {
printf("not found your full name");
}
return 0;
}
It does not work when, I use the following lines:
mohamed
ramadan
abdelrhmanamirelbatanonywoofymohamedramadanahmedalyomarelazazyahmedkamelahmedsa‌​lemessamelnaggarkhaledhelmy
It should find something, but the programm tells me, that it hasn't.
Point 1
As per the man page of strcat()
char *strcat(char *dest, const char *src);
If dest is not large enough, program behavior is unpredictable
In your case,
strcat(a,b);
a maybe not having enough memory to hold the concatenated string. Possible UB. Change the logic.
Point 2
gets() suffers from buffer overflow issue. Use fgets() instead.

char c1[ ]="abcde" works while char *c1="abcde" turns out wrong?

I was working on the "c programming language" exercise2.4, which deletes each character in s1 that matches any character in the string s2.Below is my code, it works. However,if I change the definition in Main function from char c1[ ]="abcde" to char *c1="abcde", it will turns out segmentation fault(core dumped). Any idea why?
#include<stdio.h>
#define UNREPEAT 1
#define REPEAT 0
void squeeze(char *s1,char *s2);
void main(){
char c1[]="abcde";
char c2[]="cd";
printf("c1 is %s\n",c1);
squeeze(c1,c2);
printf("the final result is %s\n",c1);
}
void squeeze(char *s1,char *s2){
int i,j,judge;
int k=0;
for(i=0;*(s1+i)!='\0';i++){
judge=UNREPEAT;
for(j=0;*(s2+j)!='\0';j++){
if (*(s1+i)==*(s2+j)){
judge=REPEAT;
break;}
}
if( judge==UNREPEAT){
* (s1+k)=*(s1+i);
k++;}
}
*(s1+k)='\0';
}
Because
char c1[] = "abcde";
declares an array, it's readable and writable and will always have 6 bytes (if you consider the terminating '\0') you can't extend it but of course you can use it to store less bytes.
While
char *c1 = "abcde";
is a static string literal it shall not be modified, you should always declare string literals using the const qualifier, that way the compiler would warn you if you try to modify its contents, which is illegal, just use
const char *c1 = "abcde";
char *c1="abcde"
This is a string literal which is read-only and in your function you try to change the contents of it so you might hit seg fault.
Whereas the other case
char c1[] = "abcde";
You are allocating memory on the stack whose contents can be modified.
PS: String literals are read-only

C programming strcat using pointer

I am a beginner in C. I wanted to make strcat function using pointers. I made it but don't know what is wrong with it. I used gcc compiler and it gave segmentation fault output.
#include<stdio.h>
#include<string.h>
char scat(char *,char *);
void main()
{
char *s="james";
char *t="bond";
char *q=scat(s,t);
while(*q!='\0') printf("the concatenated string is %c",*q);
}
char *scat(char *s,char *t)
{
char *p=s;
while(*p!='\0'){
p++;
}
while(*t!='\0'){
*p=*t;
p++;
t++;
}
return p-s-t;
}
This one works:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *scat(char *,char *); /* 1: your prototype was wrong */
void main()
{
char *s="james";
char *t="bond";
char *q=scat(s,t);
printf("cat: %s\n", q); /* 2: you can use %s to print a string */
free(q);
}
char *scat(char *s,char *t)
{
char *p=malloc(strlen(s)+strlen(t)+1); /* 3: you will have to reserve memory to hold the copy. */
int ptr =0, temp = 0; /* 4 initialise some helpers */
while(s[temp]!='\0'){ /* 5. use the temp to "walk" over string 1 */
p[ptr++] = s[temp++];
}
temp=0;
while(t[temp]!='\0'){ /* and string two */
p[ptr++]=t[temp++];
}
return p;
}
You have to allocate new space to copy at the end of s. Otherwise, your while loo[ will go in memory you don't have access to.
You shoul learn about malloc() here.
It is undefined behaviour to modify a string literal and s, and eventually p, is pointing to a string literal:
char* s = "james";
s is passed as first argument to scat() to which the local char* p is assigned and then:
*p=*t;
which on first invocation is attempting to overwite the null character an the end of the string literal "james".
A possible solution would be to use malloc() to allocate a buffer large enough to contain the concatentation of the two input strings:
char* result = malloc(strlen(s) + strlen(p) + 1); /* + 1 for null terminator. */
and copy them into it. The caller must remember to free() the returned char*.
You may find the list of frequently asked pointer questions useful.
Because p goes till the end of the string and then it starts advancing to illegal memory.
That is why you get segmentation fault.
It's because s points to "james\0", string literal & you cannot modify constant.
Change char *s="james"; to char s[50]="james";.
You need to understand the basics of pointers.
a char * is not a string or array of characters, it's the address of the beginning of the data.
you can't do a char * - char* !!
This is a good tutorial to start with
you will have to use malloc
You get a segmentation fault because you move the pointer to the end of s and then just start writing the data of p to the memory directly following s. What makes you believe there is writable memory available after s? Any attempt to write data to non-writable memory results in a segmentation fault and it looks like the memory following s is not writable (which is to expect, since "string constants" are usually stored in read-only memory).
Several things look out of order.
First keep in mind that when you want to return a pointer to something created within a function it needs to have been malloc'ed somewhere. Much easier if you pass the destination as an argument to the function. If you follow the former approach, don't forget to free() it when you're done with it.
Also, the function scat has to return a pointer in the declaration i.e. char *scat, not char scat.
Finally you don't need that loop to print the string, printf("%s", string); will take care of printing the string for you (provided it's terminated).
At first, your code will be in infinte loop because of the below line. you were supposed to use curely braces by including "p++; t++ " statements.
while(*t!='\0')
*p=*t;
though you do like this, you are trying to alter the content of the string literal. which will result in undefined behavior like segmentation fault.
A sequence of characters enclosed with in double quotes are called as string literal. it is also called as "string". String is fixed in size. once you created, you can't extend its size and alter the contents. Doing so will lead to undefined behavior.
To solve this problem , you need to allocate a new character array whose size is sum of the length of two strings passed. then append the two strings into the new array. finally return the address of the new array.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* scat(char *,char *);
void append(char *t , char *s);
int main(void)
{
char *s="james";
char *t="bond";
char *n = scat(s,t);
printf("the concatenated string is %s",n);
return 0;
}
char* scat(char *s,char *t)
{
int len = strlen(s) + strlen(t);
char *tmp = (char *)malloc(sizeof(char)* len);
append(tmp,s);
append(tmp,t);
return tmp;
}
void append(char *t , char *s)
{
//move pointer t to end of the string it points.
while(*t != '\0'){
t++;
}
while( *s != '\0' ){
*t = *s;
t++;
s++;
}
}

Resources