赛格故障当试图追加字符串 [英] Seg Fault when attempting to append strings

查看:115
本文介绍了赛格故障当试图追加字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个字符串追加到另一个,而且我得到一个赛格故障似乎并不能找出我做错了。

I'm trying to append a string to another one, and I'm getting a seg fault and can't seem to figure out what I'm doing wrong.

typedef char * String;
String function(String str) {
    // Some variables here
    String current = "";
    String ch = "";

    //More code here
    while() {
        if() {
            current = malloc(strlen(current) + strlen(ch) + 1);
            strcat(current, ch);
        }
     ...
     }
}

我总是收到赛格故障甚至注释掉 strcat的行,并用的malloc 行反之亦然。这可能是一些非常明显我失踪,但也有人解释如何做到这一点正确的做到这一点,并解释我做了什么错?

I keep getting a seg fault even with the strcat line commented out, and vice versa with the malloc line. This is probably something painfully obvious that I'm missing, but could someone explain how to do this properly do this, and explain what I've done wrong?

推荐答案

电流不是'\\ 0'后终止的malloc 。结果
strcat的正在寻找这个人物知道在哪里追加和段错误这样做。结果
结果
你的previous初始化电流的malloc 返回后没有任何意义,它指向未初始化的内存完全不同的组成部分。结果
不能告诉是肯定的,但是从你提供我的技巧是使用的realloc 延长的大小电流

current is not '\0' terminated after malloc.
strcat is searching for this character to know where to append and segfaults doing this.

Your previous initialization of current has no meaning after malloc returns, it points to completely different part of uninitialized memory.
Can't tell for sure, but from what you provided my tip is to use realloc to extend size of current.

这篇关于赛格故障当试图追加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆