This question already has answers here:
Can a local variable's memory be accessed outside its scope?
                                
                                    (20个答案)
                                
                        
                                6个月前关闭。
            
                    
我多次调用返回char值的函数时遇到问题。
我想将该函数的返回值重新分配给另一个函数中的char变量。
这是我调用函数init_current()的函数代码:

int current_live_read(int *current)
{

    char ainpath[33];
    ainpath[33]=init_current();

    char *filename = ainpath;
    int curr;

    FILE *file = fopen(filename, "r");
    fscanf(file, "%4d", &curr);
    if(!feof (file))
    {

    }
    fclose(file);

    *current=curr;
    return(0);
}


在此函数中,我将调用函数init_current()。当我第一次调用它时,我具有正确的ainpath [33]变量返回值。但是,当我第二次调用current_live_read(int * current)时,在fscanf中出现错误时,第二次调用后会出现变量ainpath [33]为“ Name:ainpath
    详细信息:“ \ 0”,“ \027Î001\0Túÿ¾\ 0 \037ã\ 225r.16 \ 0 \ 0 \ b \ 0”
    默认值:0xbefffa28
    小数:-10905205​​36”,这肯定不正确。我认为我需要以某种方式释放数组ainpath [33],但我不知道如何。

这是init_current()的代码:

char init_current(void)
{
    system("sudo echo cape-bone-iio > /sys/devices/bone_capemgr.*/slots");  //Init ADC
    system(AINpath);

    //int file;
    char ainpath[33];
    char *filename = "/root/LED_Tester_V1/CurrentRead/pathbuf";
    char * buffer = 0;
    long length;
    FILE * f = fopen (filename, "rb");

    if (f)
    {
      fseek (f, 0, SEEK_END);
      length = ftell (f);
      fseek (f, 0, SEEK_SET);
      buffer = malloc (length);
      if (buffer)
      {
        fread (buffer, 1, length-1, f);
      }
      fclose (f);
    }

    if (buffer)
    {
      sprintf(ainpath, "%s%d", buffer, AIN);

    }
    return(ainpath);
}

最佳答案

这里有很多错误。

return(ainpath);


您正在将指针返回到本地数组,该数组将在函数退出时销毁。而是分配更多的内存:

buffer =  malloc(length+10); // I don't know what AIN is, but it has to fit!


然后写入buffer,而不是ainpath并返回它,因为它在函数调用之间仍然存在。

if (buffer)
{
    sprintf(buffer, "%s%d", buffer, AIN);
}

return buffer; // return the malloc'd buffer here


由于我们要返回一个指针,因此init_current应该定义为(请注意*):

char *init_current(void)
{
...


最后,

ainpath[33]=init_current();


不按照您的想法去做。它采用init_current()作为指针返回的值,并将其存储到ainpath中的第34个字符,这可能不是您想要的。使用指针代替:

int current_live_read(int *current)
{

    char* ainpath;
    ainpath=init_current();

    int curr;

    FILE *file = fopen(ainpath, "r");
    free(ainpath); // Free when you are done using the buffer

    if(!file)
        return -1;

    fscanf(file, "%4d", &curr);
    if(!feof (file))
    {

    }
    fclose(file);

    *current=curr;
    return(0);
}

关于c - 可用的Char内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57674194/

10-14 07:49