【发布时间】:2020-01-23 08:23:55
【问题描述】:
我正在使用 Tensorflow 2.1 git master 分支(提交 id:db8a74a737cc735bb2a4800731d21f2de6d04961)并在本地编译它。使用 C API 调用TF_LoadSessionFromSavedModel,但似乎出现分段错误。我已经设法深入了解下面示例代码中的错误。
TF_NewTensor 调用崩溃并导致分段错误。
int main()
{
TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1);
int ndims = 1;
int64_t* dims = malloc(sizeof(int64_t));
int ndata = sizeof(int32_t);
int32_t* data = malloc(sizeof(int32_t));
dims[0] = 1;
data[0] = 10;
// Crash on the next line
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR");
}
else
{
printf("OK");
}
return 0;
}
但是,当我在 TF_NewTensor 调用之后移动 TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1); 时,它不会崩溃。如下:
int main()
{
int ndims = 1;
int64_t* dims = malloc(sizeof(int64_t));
int ndata = sizeof(int32_t);
int32_t* data = malloc(sizeof(int32_t));
dims[0] = 1;
data[0] = 10;
// NO more crash
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR");
}
else
{
printf("OK");
}
TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1);
return 0;
}
这是一个可能的错误还是我用错了?我不明白mallocq 自变量如何导致分段错误。
任何人都可以复制吗?
我正在使用 gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008 进行编译。
更新:
可以进一步简化错误如下。这甚至没有分配InputValues。
#include <stdlib.h>
#include <stdio.h>
#include "tensorflow/c/c_api.h"
int main()
{
int ndims = 1;
int ndata = 1;
int64_t dims[] = { 1 };
int32_t data[] = { 10 };
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR Tensor");
}
else
{
printf("OK");
}
return 0;
}
编译
gcc -I<tensorflow_path>/include/ -L<tensorflow_path>/lib test.c -ltensorflow -o test2.out
解决方案
正如 Raz 指出的那样,传递空的 deallocater 而不是 NULL,并且 ndata 应该是字节大小。
#include "tensorflow/c/c_api.h"
void NoOpDeallocator(void* data, size_t a, void* b) {}
int main(){
int ndims = 2;
int64_t dims[] = {1,1};
int64_t data[] = {20};
int ndata = sizeof(int64_t); // This is tricky, it number of bytes not number of element
TF_Tensor* int_tensor = TF_NewTensor(TF_INT64, dims, ndims, data, ndata, &NoOpDeallocator, 0);
if (int_tensor != NULL)\
printf("TF_NewTensor is OK\n");
else
printf("ERROR: Failed TF_NewTensor\n");
}
在我的 Github 上查看运行/编译 TensorFlow 的 C API here的完整代码
【问题讨论】:
-
我没有看到
InputValues在任何地方使用,那么这怎么可能是导致崩溃的原因? -
malloc的InputValues是否成功?我没有看到你检查。如果它失败了,那么在你的第一个代码中,其他 malloc 也可能失败。 -
ndata是否表示data的大小?因为你只分配了一个 int32 给它。 -
@PaulOgilvie 在这个例子中我没有使用
InputValues,但在实际代码中,我使用它来调用SessionRunAPI。malloc确实返回非空值,我也尝试使用ndata = 1,正如 Raz Haleva 所建议的那样。还是一样的分段错误 -
@PaulOgilvie 查看仍然产生分段错误的更新代码。
标签: c++ c linux tensorflow tensorflow-c++