【问题标题】:error creating buffer to load data创建缓冲区以加载数据时出错
【发布时间】:2015-01-18 16:38:58
【问题描述】:

我在从文件加载数据时遇到问题。 这段代码用一些随机数据填充高分(仅用于调试)

int i = 0; 
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
    high_score_name[i] = al_ustr_new("123456789012345678901");
    high_score[i] = 1000*i;
}

之后我将所有内容保存到文件中。

ALLEGRO_FILE* high_score_file = al_fopen("hs.txt","wb");
for (i = 0; i < MAX_HIGH_SCORE; i++)
{
    int buffer = al_ustr_size(high_score_name[i]);
    al_fwrite32le(high_score_file, buffer);
    al_fwrite(high_score_file, al_cstr(high_score_name[i]), buffer);
    al_fwrite(high_score_file, &high_score[i], sizeof(high_score[i]));

}
al_fclose(high_score_file);

它工作得很好。它有 4 个字节为大小保留,然后是 21 个字符的 high_score_name[],然后是 high_score[] int,它也占用 4 个字节。

当我尝试加载它时问题就开始了。我尝试了很多方法,但它不会编译,因为行

char* buffer= al_malloc(size); 给出错误:

“void *”类型的值不能用于初始化“char *”类型的实体

for (i = 0; i < MAX_HIGH_SCORE; i++)
{
    int size = al_fread32le(high_score_file);
    char* buffer = al_malloc(size);
    al_fread(high_score_file, buffer, size);
    high_score_name[i] = al_ustr_new_from_buffer(buffer, size);

    int *buffer2 = &high_score[i];          
    al_fread(high_score_file, buffer2, sizeof(high_score[i]));

    al_free(buffer);
}

al_fclose(high_score_file);

我坚持了两天,我真的很感激任何帮助。

【问题讨论】:

  • 尝试在调用al_malloc( )之前添加演员表,即char *buffer = (char *) al_malloc(size);
  • 它帮助解决了错误,但现在我得到 0xC0000005:初始化大小时访问冲突读取位置 0xFEEEFEF6。
  • 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory stackoverflow.com/a/127404/487892
  • 失败时 al_fread32le( ) 返回 -1。在 al_malloc( ) 调用之前需要一个 if 语句来确保 size > 0。
  • 我在使用al_fread32le(); 后添加了if(size&gt;0) 语句,但是当程序执行int size = al_fread32le(high_score_file); 时出现访问冲突@ 大小值是-858993460 并且在文件中它的15 00 00 00(即21十进制)

标签: c++ allegro5


【解决方案1】:

malloc 的输出类型为 void*,您应该尝试将其显式转换为 char*。

char* buffer = static_cast<char *>(al_malloc(size))

【讨论】:

    【解决方案2】:

    如果您的函数在内部使用 malloc 分配内存,则 malloc 返回 void*,如果您的 al_malloc 返回 void*...使用类型转换将其转换为 char*。

    char* 缓冲区 = (char*)al_malloc(size);

    这应该可行。

    malloc的函数原型:

      void *malloc(size_t size);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      相关资源
      最近更新 更多