gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:21:55 26 4
gpt4 key购买 nike

我有一个以下函数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 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

关于c - memcpy 在具有指向指针参数的指针的不同函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28154972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com