首页 > 解决方案 > 字符串的内存分配

问题描述

Bus error: 10只是通过运行以下代码来获得(在运行时):

char *x;
char *y = "the quick";
sprintf(x, "%s brown fox jumps over the lazy dog", y);

环顾四周,我看到了一些帖子,问题似乎是我正在尝试修改字符串文字,但在上面的代码中,我想,我不是。此外,如果我尝试分配一些内存来x使用malloc一切正常,而且如果我分配的内存少于存储整个字符串所需的内存,即使我 allocate 也可以0

char *x = malloc(0);
char *y = "the quick";
sprintf(x, "%s brown fox jumps over the lazy dog", y);
printf("%s\n", x); // the quick brown fox jumps over the lazy dog

我也明白这在某种程度上与内存分配有关,但我想指定x而不告诉编译器它将占用多少内存,因为y可能是一个非常长的字符串,甚至是一个数字......

我应该如何做我想做的事情,只使用 char 指针(而不是 char 数组),而不必知道 的最终长度x,例如,不必计算 的最大大小x然后分配它的内存?

标签: cprintfmalloc

解决方案


问题是x在您尝试分配后没有指向有效的内存块0。要将这两个字符串成功地连接到一个新分配的块中,您需要知道同时保存这两个字符串所需的字符总数。获得总数的一种方便方法是使用:

snprintf (NULL, 0, "format-string", vars, ...);

这将返回组合字符串所需的字符总数。然后,您分配total + 1为 nul 终止字符提供空间。你可以这样做:

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

int main (void) {
    
    char *x;
    char *y = "the quick";
    
    /* use snprintf (NULL, 0, "format", vars...) to get no. of chars needed */
    size_t needed = snprintf (NULL, 0, "%s brown fox jumps over the lazy dog", y);
    
    x = malloc (needed + 1);    /* allocate for x, +1 for the nul-terminating char */
    if (!x) {                   /* validate EVERY allocation */
        perror ("malloc-x");
        return 1;
    }
    
    /* now use sprintf to joins string in newly allocated block */
    sprintf (x, "%s brown fox jumps over the lazy dog", y);
    
    puts (x);       /* output result */
    free (x);       /* don't forget to free what you allocate */
}

示例使用/输出

$ ./bin/snprintfNULL0
the quick brown fox jumps over the lazy dog

内存使用/错误检查*

在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您有两个责任:(1)始终保留指向内存块起始地址的指针,(2)它可以在没有时被释放更需要。

您必须使用内存错误检查程序,以确保您不会尝试访问内存或写入超出/超出分配块的边界,尝试读取或基于未初始化值的条件跳转,最后确认释放所有分配的内存。

对于 Linuxvalgrind是正常的选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。

$ valgrind ./bin/snprintfNULL0
==31830== Memcheck, a memory error detector
==31830== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==31830== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==31830== Command: ./bin/snprintfNULL0
==31830==
the quick brown fox jumps over the lazy dog
==31830==
==31830== HEAP SUMMARY:
==31830==     in use at exit: 0 bytes in 0 blocks
==31830==   total heap usage: 2 allocs, 2 frees, 1,069 bytes allocated
==31830==
==31830== All heap blocks were freed -- no leaks are possible
==31830==
==31830== For counts of detected and suppressed errors, rerun with: -v
==31830== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认您已释放所有已分配的内存并且没有内存错误。

看看这个,如果你有问题,请告诉我。


推荐阅读