You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

禁止动态内存分配时,如何解决结构体嵌套指针的字符填充问题?

解决结构体嵌套指针字符数组赋值的段错误问题(禁止动态内存分配)

嘿,我来帮你搞定这个段错误的问题!

首先得说清楚你代码里的核心问题:你声明的custom_string_container里的string是个指针,但在main函数里你只是创建了custom_string_container的实例,却从来没让这个指针指向一块有效的内存空间——它是个野指针!当你尝试通过这个野指针去给textt数组赋值时,自然会触发段错误(退出码139就是典型的非法内存访问错误)。

因为你被严格禁止使用动态内存分配,那我们只能用栈上的内存来解决,这里有两种靠谱的方案:

方案一:在栈上创建custom_string实例,让指针指向它

这种方案不需要修改结构体定义,只需要调整main函数,给指针绑定一个栈上的有效结构体实例:

typedef struct custom_string { char textt[5]; int length; }custom_string;
typedef struct custom_string_container { custom_string* string; }custom_string_container;

void read_string_from_byte_array(custom_string_container* string_container) {
    char* byte_array = "12345";
    int i;
    puts("assigning");
    for(i = 0; i < 5; i++) {
        string_container->string->textt[i] = byte_array[i];
    }
    // 手动添加字符串终止符,避免printf输出乱码
    string_container->string->textt[5] = '\0';
    string_container->string->length = 5;
    puts("done assigning");
}

void main() {
    //dynamic memory allocation is strictly prohibited
    custom_string_container string_container;
    custom_string str_instance; // 在栈上创建custom_string的实例
    string_container.string = &str_instance; // 让指针指向这个栈上的实例
    read_string_from_byte_array(&string_container);
    printf("read string is %s \n", string_container.string->textt);
}

方案二:把结构体里的指针改成直接包含结构体

如果不需要指针的灵活性,直接把custom_string_container里的指针换成值类型的结构体,这样就完全不用处理指针指向的问题了:

typedef struct custom_string { char textt[6]; int length; }custom_string; // 把数组大小改成6,预留终止符位置
typedef struct custom_string_container { custom_string string; }custom_string_container; // 替换指针为结构体实例

void read_string_from_byte_array(custom_string_container* string_container) {
    char* byte_array = "12345";
    int i;
    puts("assigning");
    for(i = 0; i < 5; i++) {
        string_container->string.textt[i] = byte_array[i]; // 用.访问结构体成员,不再需要->
    }
    string_container->string.textt[5] = '\0';
    string_container->string.length = 5;
    puts("done assigning");
}

void main() {
    //dynamic memory allocation is strictly prohibited
    custom_string_container string_container;
    read_string_from_byte_array(&string_container);
    printf("read string is %s \n", string_container.string.textt);
}

额外提醒

注意你的textt数组大小:字符串字面量"12345"实际包含5个字符加一个隐藏的\0终止符,所以如果直接用char textt[5]的话,赋值后数组里没有终止符,用printf("%s")输出会出现未定义行为(比如乱码)。所以要么把数组大小改成6,要么在赋值后手动添加\0,上面的两种方案都已经处理了这个问题。

内容的提问来源于stack exchange,提问作者salimsaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:16:57