我是一个学习C的初学者。根据我所学到和阅读的内容here例如,当您不知道编译时所需的内存量时,可以使用 malloc()。我正在编写代码,其中我知道要声明的字符串的长度,但如果不使用 malloc() 为其分配内存,则会出现错误,并且我不明白为什么。
我正在编写的代码是针对哈佛 CS50 问题集,其中的目标是恢复已删除的 jpg,但我已将其精简以仅显示此问题。我的代码显示了两行声明 char* 文件名的行,其中导致错误的行被注释掉。这两个选项都可以编译,没有 malloc() 的选项会在运行时导致 UndefinedBehaviorSanitizer:DEADLYSIGNAL 错误。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// remember filenames
char *infile = argv[1];
//open input file
FILE *inptr = fopen(infile, "r");
//buffer
BYTE buffer[512];
//read first 512 byte block in to buffer
size_t r = fread(&buffer, 1, 512, inptr);
int n = 0;
//get name for new jpg file
//char *filename[8]; //<<<<<<<<<<<<<<<<<<<<<this causes error
char *filename = malloc(8);
sprintf(filename, "%03i.jpg", n);
}
错误如下:
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==5563==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc 0x7fb433fba0ac bp 0x000000000030 sp 0x7ffd5af8a290 T5563)
==5563==The signal is caused by a WRITE memory access.
==5563==Hint: address points to the zero page.
#0 0x7fb433fba0ab (/lib/x86_64-linux-gnu/libc.so.6+0x900ab)
#1 0x7fb433fb8493 (/lib/x86_64-linux-gnu/libc.so.6+0x8e493)
#2 0x7fb433faa37d (/lib/x86_64-linux-gnu/libc.so.6+0x8037d)
#3 0x7fb433f86f1f (/lib/x86_64-linux-gnu/libc.so.6+0x5cf1f)
#4 0x7fb433fab6d0 (/lib/x86_64-linux-gnu/libc.so.6+0x816d0)
#5 0x7fb433f8f093 (/lib/x86_64-linux-gnu/libc.so.6+0x65093)
#6 0x428049 (/home/ubuntu/pset3/recover/malloc+0x428049)
#7 0x7fb433f4bb96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#8 0x402ad9 (/home/ubuntu/pset3/recover/malloc+0x402ad9)
UndefinedBehaviorSanitizer can not provide additional info.
==5563==ABORTING
最佳答案
char *filename[8];
好的,我们声明一个包含 8 个字符指针的数组,不初始化任何指针,并将其中一个传递给 sprintf
目标。
您的工作代码是
char *filename = malloc(8);
它清楚地声明了一个指针,并使用指向堆外 8 个字节的指针对其进行初始化。因此,你想要
char filename[8];
它声明了一个 8 个字符的数组。
关于c - 了解何时需要 malloc() : I know the length of char * n at compile time yet still seem to need malloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57028903/