【问题标题】:Problems with Memmove and SIGSEGV in CC 中的 Memmove 和 SIGSEGV 问题
【发布时间】:2013-06-17 12:57:37
【问题描述】:

我在 C 中的 memmove 遇到了一些问题。据我所知,这两个位置都是有效的内存地址,我可以在执行 memmove 之前打印两个内存位置的内容,但是只要我尝试 memmove 时,函数会因 SIGSEGV 崩溃。

这里是有问题的代码:

std::cout << page[0] << "\n";
std::cout <<page[1] << "\n" ;
std::cout << cache[index][cache_itr] << "\n";

memmove(cache[index][cache_itr],page,sizeof(float));

//These lines never print.
std::cout << cache[index][cache_itr] << "\n";
std::cout << cache[index][cache_itr] << "\n";

缓存被声明为 float** ,而 page 是一个 float* ,其中包含一个可变大小的浮点数组。然而,数组的大小不太可能成为问题,因为我什至无法将它复制到单个浮点数上,尽管 page 无疑包含一个浮点数,这可以从 page[0] 和 page 的有效打印中得到证明[1]。

Cache[0] 和 Cache[1] (索引永远只会是 0 或 1,这也得到确认)都是指向结构对象中的 float** 的先前 calloc-ed 缓存的指针。可以在这里看到:

float** cache[2];
cache[0] = queryOb->cache;
cache[1] = cache[0] + sizeOfCache/2;

sizeOfCache 最初用于声明我们要为 queryOb->cache 调用多少个大小为 float* 的块。

我一生都无法弄清楚为什么这个 memmove 会产生 sigsegv,我相信这可能与 memmove 从 float* 到 float** 有关,但是我认为使用memmove 会导致它开始复制到正确的位置。

任何帮助将不胜感激!

【问题讨论】:

  • memmove的最后一个参数是字节数
  • 我知道,我现在只是想让它复制一个浮点数,它不能这样做

标签: c segmentation-fault memmove


【解决方案1】:

Memmove的定义是

void* memmove( void* destination, const void* source, size_t num );

你正在调用函数

memmove(cache[index][cache_itr], page, sizeof(float);

刚刚注意到cache[index][cache_itr] 是存在于的数组元素的值 假设(对于 index =2,cache_itr =3)位置 cache[2][3]

您需要提供一个指针而不是值。改成

 memmove(cache[index], page, sizeof(float));

会有意义。

此外,编译器在编译此代码时应该抛出警告“从整数中生成指针而不进行强制转换”。

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多