c++ - 为什么不返回 NULL 会破坏函数?
问题描述
因此,我的任务是制作并返回给定字符串的副本,以防万一它失败(例如,按 Enter)返回 NULL。但是,当我按 Enter 时,程序继续工作并打印出一些垃圾值。有趣的事实是,当我通过调试器运行程序时,程序运行良好(这对我来说是最大的挑战)。对于可能出现的问题,我找不到简单的解释。还是我的编译器有问题?
#include <stdio.h>
#include <stdlib.h>
// listing functions
char *ft_strdup(char *src);
int main(void)
{
// input of a string
char c[200];
scanf("%[^\n]%*c", c);
// calling a function
char *f = ft_strdup(c);
printf("\n%s\n", f);
free(f);
return 0;
}
char *ft_strdup(char *src)
{
int i = 0;
// itearting to get the 'length' of string src
while (src[i] != '\0')
++i;
// if user has inputted nothing - return NULL and break the function
if (i == 0)
{
return NULL;
}
// otherwise, make a copy of the string
char *x = malloc(i+1);
int j = 0;
while (j != i)
{
x[j] = src[j];
++j;
}
x[i+1] = '\0';
// print out and return
printf("%s\n%s\n%i", x, src, i);
return x;
}
解决方案
它打印垃圾值,因为 char c[200]; 没有初始化,这意味着它里面有垃圾值。
char c[200] = {0};
试试这个,可能会因为 NULL 指针访问而崩溃。
添加这个以避免崩溃
if (f != NULL) {
printf("\n%s\n", f);
free(f);
}
推荐阅读
- scala - sql.DataFrame 类型的表达式不符合预期的类型 Option[sql.DataFrame]
- node.js - 在 Node.js 中重定向发布请求
- jupyter-notebook - Jupyter notebook 无法在浏览器中看到任何内容
- reactjs - 无法检查语义 UI 反应组件的 expect(elm).not.toBeVisible()
- apache-kafka - 如何管理 Kafka 连接架构错误?
- c# - 有没有办法继续使用已弃用的 .net 系统库?
- c# - 检查属性值是否等于对象列表中的预定义值
- vim - 为什么在宏内改变单词的大小写会改变行为?
- hadoop - 如何根据 hive 中的 3 列查找上一个日期值
- django - 姜戈休息。按计算模型字段排序