我只是通过运行以下代码获得 Bus error: 10
(在运行时):
char *x;
char *y = "the quick";
sprintf(x, "%s brown fox jumps over the lazy dog", y);
Looking around 我看了几篇帖子,问题好像是我想修改一个字符串文字,但是在上面的代码中,我想,我不是。
此外,如果我尝试使用 x
为 malloc
分配一些内存,一切正常,而且如果我分配的内存少于存储整个字符串所需的内存,即使我分配了 {{1} }.
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
的最终长度,例如无需计算 x
的最大大小然后分配内存?
答案 0 :(得分:2)
问题是在您尝试使用 x
进行分配后,0
没有指向有效的内存块。要成功地将两个字符串连接到新分配的块中,您需要知道保存这两个字符串所需的字符总数。获得总数的一种便捷方法是使用:
snprintf (NULL, 0, "format-string", vars, ...);
将返回组合字符串所需的总字符数。然后分配 total + 1
为空终止字符提供空间。你可以这样做:
#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
内存使用/错误检查*
在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您有 2 个责任:(1) 始终保留一个指向起始地址的指针内存块,(2) 可以在不再需要时释放。
您必须使用内存错误检查程序来确保您不会尝试访问内存或超出/超出分配块的范围进行写入,尝试读取或基于未初始化值的条件跳转,最后, 以确认您释放了所有分配的内存。
对于 Linux valgrind
是正常选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。
$ 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)
始终确认您已释放分配的所有内存,并且没有内存错误。
看看这个,如果你有问题,请告诉我。
答案 1 :(得分:1)
sprintf
存储字符串,包括指定到由其第一个参数指向的数组中的转换。为转换后的字符串传递一个足够大的数组是程序员的责任,包括它的最终终止符。
在您的第一个示例中,通过未初始化的指针写入具有未定义的行为,这可能会导致您观察到的崩溃。
在第二个示例中,malloc(0)
可能返回 NULL
或不应用于写入的有效指针,因为它指向大小为 0
的数组。在这两种情况下,sprintf
都会调用未定义的行为,在这种情况下,您测试时的机器会产生预期的行为,因为无效的写入未被检测到,但可能会导致稍后可见的副作用。
这是修改后的版本:
char x[80];
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
使用 snprintf()
并传递目标数组的实际大小来避免未定义行为(如果它碰巧太短)要安全得多。字符串将被截断以适合数组,但返回值将是转换生成的总字节数:
char x[25];
char *y = "the quick";
int n = snprintf(x, sizeof x, "%s brown fox jumps over the lazy dog", y);
printf("%s, needs %d bytes\n", x, n + 1); // the quick brown fox jump, needs 44 bytes
您可以通过使用空指针和零大小调用 snprintf
来确定所需的大小:
size_t minimum_size = 1 + snprintf(NULL, 0, "%s brown fox jumps over the lazy dog", y);
某些系统还具有自动分配所需内存的替代函数 asprintf
,但这是一个未广泛使用的 GNU 扩展。
答案 2 :(得分:1)
坏消息是,你不能不计算缓冲区的最终大小。
好消息是您可以让 snprintf 为您计算。
const char *y = "the quick";
const char *fmt = "%s brown fox jumps over the lazy dog";
int sizeneeded = snprintf(NULL, 0, fmt, y) + 1;
char *dest = malloc(sizeneeded);
snprintf(dest, sizeneeded, fmt, y);
printf("%s\n", dest); // the quick brown fox jumps over the lazy dog
免责声明:为简洁起见,此处未针对 malloc
检查 NULL
的返回值。
答案 3 :(得分:1)
...问题似乎是我试图修改一个字符串文字,但在上面的代码中,我想,我不是。
正确,您没有修改 ant 字符串文字。 y
指向字符串文字,但没有代码通过 y
对字符串进行修改。
问题(在第一个代码片段中)是 x
未初始化。
malloc
解决了这个问题,但又出现了一个新问题。在您编写时,您分配的内存太少。
...问题似乎是我试图修改一个字符串文字,但在上面的代码中,我想,我不是。
现在怎么可能?
发生的情况是您写入数组外的内存(越界访问)。 C 标准将其定义为“未定义行为”。
“未定义行为”意味着任何事情都可能发生。例如,允许程序崩溃。但该程序也可能(似乎)像您预期的那样工作。这发生在你身上......你的代码是错误的 - 有未定义的行为 - 但幸运的是(或者更不幸的是)它似乎可以工作。