简体   繁体   中英

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

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM