apkim221
apkim221

Reputation: 121

What is wrong with this concatenation function in C?

this is part of a homework assignment using structs and I can't seem to understand this one function. The function is string_t *concat (string_t *s1, string_t *s2) and it returns the new string struct. This is what I have so far, and it crashes the compiler whenever it's reached. The program compiles but, "file".exe has stopped working error comes up when executing. Any help would be greatly appreciated. Thanks!

typedef struct string{ //String struct (in .h file)

char *line;
int length;

} string_t;


string_t* concat(string_t *s1, string_t *s2) { //actual function (in .c)

int len1, len2;
len1 = length(s1);
len2 = length(s2);

int i, j, s;

string_t *newStr;
newStr = (string_t*)malloc(sizeof(string_t)*2);


for (i = 0; i<len1; i++) {
    *((newStr->line)+i) = *((s1->line)+i);
    }

for (j=0; j<len2; j++) {
    *((newStr->line)+(i+j)) = *((s2->line)+j);
    }

*((newStr->line)+(i+j))='\0';

return newStr;

}



concat(s1, s2); //tests function

Upvotes: 0

Views: 92

Answers (2)

Josh Petitt
Josh Petitt

Reputation: 9579

BTW, here's a way to cat without that ugly ptr math syntax:

char* dest = newStr->line;

const char* src = s1->line;
while (*src)
{
  *dest = *src;
  ++dest;
  ++src;
}

src = s2->line;
while (*src)
{
  *dest = *src;
  ++dest;
  ++src;
}

*dest = '\0';

Upvotes: 0

cnicutar
cnicutar

Reputation: 182649

newStr = (string_t*)malloc(sizeof(string_t)*2);

You allocate memory for newStr but you don't allocate memory for newStr->line. Try something like:

newStr = malloc(sizeof *newStr);
newStr->line = malloc(s1->length + s2->length + 1);

Side note: *((newStr->line)+i) can be written as newStr->line[i].

Upvotes: 4

Related Questions