【发布时间】:2018-03-10 19:27:57
【问题描述】:
程序的目标是从终端获取用户输入,然后打印出用户输入的每个单词的最后一个字符。
例如,“Hello World”应该打印出“od”。
这里是代码。当我尝试调整 char 指针的大小时,我不确定哪里出错了。代码如下。
仅当我在 gcc 的参数中使用 -fsanitize=address 时才会出现此问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char *shortened = NULL;
int i = 1;
while(argv[i] != NULL)
{
shortened = realloc(shortened, 1 * (sizeof(char)));
int length = strlen(argv[i]);
char* curWord = argv[i];
shortened[i-1] = curWord[length -1];
i++;
}
printf("%s\n", shortened);
return 0;
}
【问题讨论】:
-
它对我有用。你在看什么?你在哪个平台上工作?
-
1不是i。 -
@Leonard 我忘了提到它只会在我在编译程序时使用 -fsanitize=address 参数时给我一个问题。没有那个,我没有问题
-
你为什么要分配任何内存?您的输入已经存在并且已经被标记化。您无需在堆外分配内存即可找到 argv[1] 到 argv[argc-1] 中的每个中的最后一个字符。
-
您需要一个额外的字节空间来为您的字符串添加一个 nul 终止符,否则 printf 将导致未定义的行为。如果您没有参数,它也是未定义的行为,因为您尝试打印 NULL。
标签: c string pointers memory-management realloc