具有指向指针参数的指针的不同函数中的 memcpy

memcpy in a different function having a pointer to pointer argument

我有一个以下函数 process 调用一个例程 dataFileBuffer,它接受一个指向指针的指针并在取消引用的指针位置执行 memcpy。

int dataFileBuffer(uint8_t *index, char **tempBuf,int size)
{   
   if(index != stop_address)) /*stop_address is a fixed pointer to the end buffer*/
   {
      if(*tempBuf)
      {
        if(index + size < stop_address)
            memcpy(*tempBuf,index,size);
        else
        {
            size  = stop_address-index-1;               
            memcpy(*tempBuf,index,size);    
        }
      }
      else
        size = 0;
  }
  else  
    size = 0;   
  return size;
}

int process()
{
    char *readBuf=NULL;    
    char *tBuf = (char *)malloc(MAX_LENGTH); 
    int readBytes = -1;
    uint8_t *index = start_address;
    uint8_t *complete = stop_address;
    do 
    {

       readBuf = tBuf+(sizeof(char)*40);
       readBytes = 0;
       readBytes = dataFileBuffer(index,&readBuf,MAX_LENGTH);
       if(readBytes > 0)
       {
           index = index+readBytes;
       }

   }while(index <= complete);
   return readBytes;
}

我的 process 函数间歇性地看到堆栈损坏,这让我觉得我的复制实现有问题。

我只是想了解我们是否可以将指向指针的指针作为参数传递并安全地 memcpy 到被调用函数中的取消引用位置?

问题的代码有几处错误。除了一些语法错误外,值得注意的是函数

dataFileBuffer(index, char **tempBuf,int size)

由于两个原因无法编译,没有为参数 index 声明类型,也没有声明 return 值 - 请注意函数以

结尾
return size;

并这样称呼:

readBytes = dataFileBuffer(index,&readBuf,MAX_LEN);

我猜应该是

int dataFileBuffer(char *index, char **tempBuf, int size)

但我很困惑为什么你为了 memcpy().

颠倒了给 dataFileBuffer() 的论点

接下来,您已使用 MAX_LENMAX_LENGTH40 定义缓冲区大小或偏移量,但没有明确定义或检查可用缓冲区的大小index 您复制到 - 或者是 from :-)。提供缓冲区大小比指针限制更常见。

你还有

...
readBytes = dataFileBuffer(index,&readBuf,MAX_LEN);
if(readBytes > 0)
    {
        index = index+readBytes;
    }
} while(index <= complete);

readBytes == 0时很可能会导致无限循环,无论如何都会在后续循环中复制相同的数据

抱歉,我无法提供合适的解决方案,因为它一团糟。

OP评论后添加

在回答有关推迟 **pointer 的具体问题时,此示例通过查找字符串长度成功地做到了这一点。

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

// return the length of the string
size_t slen(char **tempBuf)
{   
    return strlen (*tempBuf);
}

int main(void) {
    char string[] = "abcde";
    char *sptr = string;
    printf ("Length of '%s' is %d\n", string, slen (&sptr));
    return 0;
}

程序输出:

Length of 'abcde' is 5