Kundan Negi
Kundan Negi

Reputation: 41

c program of strcat using pointers

Please run it on your machine using gcc and tell if it also gives you a segmentation fault output. I don't think there is any problem with the program. I am a beginner in C. So Help!!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *scat(char *,char *);

void main()
{
    char *s="james";
    char *t="bond";

    char *w=scat(s,t);
    printf("the con: %s\n", w);
    free(w);
}

char *scat(char *s,char *t)
{ 
    char *p=malloc(strlen(s)+strlen(t)+1); 
    int temp=0 , ptr=0;

    while(s[temp]!='\0'){
        p[ptr++]=s[temp++];
    } 
    temp=0;
    while(t[temp]='\0'){
        p[ptr++]=t[temp++];
    }
    return p;
}

Upvotes: 1

Views: 310

Answers (4)

wildplasser
wildplasser

Reputation: 44250

There is no need to emulate the functions that exist in string.h:

#include <string.h>

char *scat(char *s,char *t)
{ 
    char *p;
    size_t len1, len2;
    len1 = strlen(s);
    len2 = strlen(t);

    p=malloc(len1+len2+1);
    if (!p) barf();
    memcpy(p,s, len1);
    memcpy(p+len1, t, len2+1);

    return p;
}

Upvotes: 0

StackedCrooked
StackedCrooked

Reputation: 35535

  1. Please run it on your machine using gcc and tell if it also gives you a segmentation fault output.
  2. I don't think there is any problem with the program.

I don't follow your reasoning. If the program segfaults on your system then it is very likely that the program is at fault.

FYI this is what GCC(*) outputs. It doesn't even compile.

NOTE: It's g++ actually, but it shouldn't make too much of a difference.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

The second loop has no effect:

while(t[temp]='\0') { // <<== Assignment!!!
    p[ptr++]=t[temp++];
}

This should be a != not =, or better yet, you can drop zero altogether:

while(t[temp]) { // Zero-checking is implicit in C
    p[ptr++] = t[temp++];
}

Since you are not writing to s or t, it's probably a good idea to declare them both const. This would have caught the assignment in the while loop above.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182734

You don't 0-terminate the string in scat. You could add:

p[ptr] = 0;

Right before returning.

Upvotes: 1

Related Questions