简体   繁体   English

C错答案

[英]C strlen wrong answer

I can't figure out what's wrong with my code 我无法弄清楚我的代码出了什么问题

char* readString() {

    char* result;
    char line[SIZE];

    if(! fgets(line, sizeof(line), stdin))
        fprintf(stderr, "error\n");

    //printf 1
    printf("line length = %lu\n", strlen(line));

    result = line;

    return result;
}

int main() {

    char* myWord = readString();
    unsigned long len = (unsigned)strlen(myWord);

    //printf 2
    printf("myWord length = %lu\n", len);

    return 0;
} 

If printf1 and printf2 are both uncommented then I get true length. 如果printf1和printf2都未注释,那么我得到的是真实长度。 For example for word 'hello' I have output 例如对于单词“你好”我有输出

line length = 6
myWord length = 6

but If I only comment printf1, for the same word 'hello' I have 但是如果我只评论printf1,那么对于相同的单词“ hello”,我有

myWord length = 16

Your code exhibits undefined behavior . 您的代码表现出未定义的行为 You are returning a pointer to a variable declared on the stack. 您正在返回指向在堆栈上声明的变量的指针。 In this case, line or result . 在这种情况下, lineresult

Two possible fixes include: 两个可能的修复程序包括:

  1. Pass the char line[SIZE]; 通过char line[SIZE]; variable to the readString() function. readString()函数的变量。
  2. Allocate the memory for line on the heap using malloc() . 使用malloc()在堆上为line分配内存。

You return a dynamic value (stack allocated) which is deleted by return . 您返回一个动态值(分配的堆栈),该值由return删除。 You should either 你应该

  • use a static string, but it won't support multithreading nor recursively 使用静态字符串,但它不支持多线程也不递归
  • let the caller define the string as 让调用者将字符串定义为

     char * readstring(char * line, size_t size) { // Your stuff char * result = fgets(line, size); // ... return result; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM