使用realloc时获取(核心转储) [英] Getting (core dumped) when using realloc

查看:98
本文介绍了使用realloc时获取(核心转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void replace(char *str) {
    unsigned int len = 0;
    unsigned int no_of_spaces = 0;
    while (*str) {
        if ((char)*str == SPACE)
            no_of_spaces++;
        str++;
        len++;
    }

    unsigned int new_len = len + 2 * no_of_spaces;
    str = (char*) realloc(str, new_len * sizeof(char));
    str[new_len] = '\0';
}

我使用像replace("random string");这样的功能.

在这里,我试图增加字符串的大小,以便可以用另一个字符串替换空格.为此,我需要计算空格数,并获取原始字符串的长度.我已经能够做到这一点.

Here I am trying to increase the size of the string so that spaces can be replaced with another string. For this I need to count the no of spaces and also get the length of the original string. I have been able to do that.

为了调整大小,我使用的是realloc,但运行时会显示Aborted (core dumped)?

For resizing I am using realloc but when I run it, it gives Aborted (core dumped)?

推荐答案

您原来的字符串是使用malloc分配的吗?还是重新分配?也许您正在尝试增加静态字符串(字符串文字)的大小:

Was your original string allocated using malloc? or realloc? Perhaps you are trying to increase the size of a static string (a string literal):

char sStatic[256];   // cannot realloc

char *sNonStatic = NULL;   // can / must realloc

replace("random string") // cannot realloc within replace

阅读评论后,您应该获取传入字符串的副本,增加大小,然后输出副本/新字符串.您不能增加常量字符串(字符串文字)的大小.

after reading your comment, you should take a copy of your incoming string, increase the size, then output a copy/ new string. You cannot increase the size of a constant string (a string literal).

这篇关于使用realloc时获取(核心转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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