首页 > 解决方案 > 为什么不返回 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;
}

标签: c++stringmemoryinputnull

解决方案


它打印垃圾值,因为 char c[200]; 没有初始化,这意味着它里面有垃圾值。

char c[200] = {0}; 

试试这个,可能会因为 NULL 指针访问而崩溃。

添加这个以避免崩溃

if (f != NULL) {
   printf("\n%s\n", f);
   free(f);
}

推荐阅读