2

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;
}
1
  • 1
    BTW, the main function should return an int instead of void. PLease make sure that your compiler is configered to emit warnings. Commented Jan 10, 2013 at 14:03

9 Answers 9

8

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your way of explanation was amazing by pointing out mistakes in comments. Thanks buddy !!!!!!
But this doesn't answer the question. You asked to do it with pointers instead of arrays.
3

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.

Comments

3

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.

Comments

2

Because p goes till the end of the string and then it starts advancing to illegal memory. That is why you get segmentation fault.

2 Comments

what do you mean by advancing to illegal? pointer p was incremented to till end of string,so p-s-t was done by me to reach the first address of string and then use indirection operator * to get the characters.Thanks in advance.
char *scat(char *s,char *t) { char *p=s; while(*p!='\0'){ // here means you have reached end of "string" p++; // you are advancing pointer } while(*t!='\0'){ *p=*t; p++; // here you are advancing past end of string. t++; } return p-s-t; }
0

It's because s points to "james\0", string literal & you cannot modify constant.

Change char *s="james"; to char s[50]="james";.

Comments

0

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

2 Comments

But as you said in your 2nd line that its points to addresses of the beginning of data, so that address must be in integer. So why can't i subtrat an int from int
you can and it will give you a new address but it is useless.
0

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).

Comments

0

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).

Comments

0

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++;    
    }       
}  

1 Comment

I think you have to change the code to: tmp[0] = '\0'; append(tmp,s); tmp[strlen(s)] = '\0'; append(tmp,t); tmp[len] = '\0';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.