在函数之间传递其指针后,Char数组损坏 [英] Char array corrupted after its pointer is passed between functions

查看:112
本文介绍了在函数之间传递其指针后,Char数组损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习C了几周了.我已经通过使用malloc()在堆上分配一些内存来解决了我的问题.我对为什么我的代码失败感到有些疑惑,但我不确定100%.不幸的是,我是在自学,所以我不得不求助于互联网上的好人.

I've been learning C for a few weeks. I have solved my problem by using malloc() to allocate some memory on the heap. I have an inkling about why my code failed but I'm not 100% sure. Unfortunately I am self-teaching so I have to turn to you kind people on the internet.

代码描述调用函数getString(),该函数声明一个数组,使用内置的getchar()填充该数组并返回指向该数组的指针.

Code description Calls a function getString() which declares an array, fills the array using the inbuilt getchar() and returns a pointer to that array.

问题,我打印了返回的指针值,一切正常.但是,当我将其传递给另一个简单地将其吐出并尝试打印的函数时,该字符串的末尾被截断,有时会吐出一个无用的字符.

The issue I print the returned pointer value and everything is fine. BUT when I pass it to another function that simply spits it back out and try to print that, the end of the string is cut off, sometimes it spits out a nonsense character.

我认为可能会发生的事情.原始数组仅在getString()函数&因此C正在使用数组地址中的某些内存来存储其他内容.

What I think could be happening The original array is only in use for as long as the getString() function & so C is using some of the memory in the array address to store other things.

我的直觉是正确的吗?如果没有,有人可以将我指向正确的方向吗?

Is my intuition correct? If not, could someone point me in the right direction?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 100

char * getString(void);
char * doSomethingWith(char *);

int main(void)
{
    char *string1 = getString();
    printf("String: %s\n", string1);
    char *string2 = doSomethingWith(string1);
    printf("String: %s\n", string2); // This print out is unreliable!
    return EXIT_SUCCESS;
}

char * getString(void) {
    int c;
    char arr[MAXLEN];
    char *string = arr;
    char *cur = arr;

    while((c = getchar()) != '\n' && c != EOF) {
        if(cur - string < MAXLEN - 2) {
            *cur++ = c;
        }
    }
    *cur = '\0'; // Terminate string

    return string;
}

char * doSomethingWith(char *string) {
    return string;
}

这是我修改的getString(),它的行为正确.

Here is my amended getString() which behaves correctly.

char * getString(void) {
    int c;
    char *string = malloc(sizeof *string * MAXLEN);
    char *cur = string;

    while((c = getchar()) != '\n' && c != EOF) {
        if(cur - string < MAXLEN - 2) {
            *cur++ = c;
        }
    }
    *cur = '\0'; // Terminate string

    return string;
}

更新:感谢您的所有回答!非常感谢.

Update: Thanks for all the answers! Very much appreciated.

推荐答案

getString返回具有自动存储持续时间的函数局部变量的地址,即arr的地址.函数返回后,通过该地址访问arr的任何尝试均具有未定义的行为.

getString returns the address of function local variable with automatic storage duration, the address of arr. Any attempt to access arr via that address after the function returns has undefined behavior.

C标准不能保证它将保留其值.无法保证不会.当您打破这样的语言约束时,编译器甚至没有义务生成有效的程序.

There is no guarantee by the C standard it will preserve its value. There is no guarantee it won't. There is no obligation by the compiler to even produce a valid program when you break a language constraint like that.

6.2.4对象的存储期限¶2

对象的生存期是程序执行的一部分,在此期间保证为其保留存储空间.一个对象存在,具有恒定的地址33),并在其生命周期内保留其最后存储的值.34)如果在其生命周期之外引用了一个对象,则该行为是不确定的.当指针指向的对象(或刚刚过去的对象)达到其生命周期的尽头时,指针的值将变得不确定.

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

上面提到的寿命是从getString的打开括号到关闭的括号,只要执行就可以.不多不少.

The lifetime mentioned above is from the opening brace up to the closing brace of getString, for as long as its executing only. No more, no less.

这篇关于在函数之间传递其指针后,Char数组损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆