C“重新分配”导致程序停止

问题描述 投票:-1回答:1

我正在学习C,尽管使用realloc函数遇到了一个小问题。下面的代码旨在创建两个结构,每个结构包含一个字符列表,然后将第二个字符列表添加到第一个字符的末尾,从而重新分配内存。但是,此代码可以进行realloc调用,但是以退出代码0结尾,而没有完成程序的其余部分。我无法弄清楚这里正在发生什么,任何帮助将不胜感激。

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

typedef struct String {
    char* chars;
} String;

String createString(char* chars) {
    String res;
    res.chars = chars;

    return res;
}

int main() {
    printf("Starting program!\n");

    String a = createString("Hello ");
    String b = createString("There");

    puts(a.chars);
    puts(b.chars);

    int aLength = sizeof(&a.chars) / sizeof(char);
    int bLength = sizeof(&b.chars) / sizeof(char);

    a.chars = (char*) realloc(a.chars, aLength + bLength);

    // Add b to the end of a
    for (int i = 0; i < bLength; i++) {
        a.chars[i + aLength] = b.chars[i];
    }

    puts("Complete");
    puts(a.chars);

    return 0;
}

非常感谢您的帮助!

c realloc exit-code
1个回答
0
投票

替换

  res.chars = chars;

作者

  res.chars = malloc(strlen(chars)+1);
  strcpy(res.chars, chars);
© www.soinside.com 2019 - 2024. All rights reserved.