我正在學習C,並且同時嘗試實現Python C擴展,這完美工作直到我將它傳遞給一個相當大的列表爲止......使用此Python C擴展在特定情況下獲取總線錯誤
例..
>>> import shuffle
>>> shuffle.riffle(range(100))
的偉大工程!
>>> shuffle.riffle(range(1000))
Bus Error: 10
有關我的問題是什麼的任何想法?
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static PyObject *shuffle_riffle(PyObject *self, PyObject *args)
{
int const MAX_STREAK = 10;
int m, f, l, end_range, streak, *current_ptr;
double length;
PyObject * origList;
PyObject * shuffledList;
srand((int)time(NULL));
// parse args to list
if (! PyArg_ParseTuple(args, "O!", &PyList_Type, &origList))
{
return NULL;
}
length = (int)PyList_Size(origList);
current_ptr = (rand() % 2) ? &f : &l;
end_range = (int)(length/2) + (rand() % (length > 10 ? (int)(.1 * length) : 2));
shuffledList = PyList_New((int)length);
for(m = 0, f = 0, l = (end_range + 1), streak = 0; m < length && l < length && f < end_range + 1; m++, *current_ptr += 1)
{
double remaining = 1 - m/length;
double test = rand()/(double)RAND_MAX;
if (test < remaining || streak > MAX_STREAK)
{
current_ptr = (current_ptr == &f ? &l : &f);
streak = 0;
}
PyList_SetItem(shuffledList, m, PyList_GetItem(origList, *current_ptr));
streak += 1;
}
// change the pointer to the one that didn't cause the for to exit
current_ptr = (current_ptr == &f ? &l : &f);
while(m < length)
{
PyList_SetItem(shuffledList, m, PyList_GetItem(origList, *current_ptr));
m++;
*current_ptr += 1;
}
return Py_BuildValue("O", shuffledList);
}
static PyMethodDef ShuffleMethods[] = {
{"riffle", shuffle_riffle, METH_VARARGS, "Simulate a Riffle Shuffle on a List."},
{NULL, NULL, 0, NULL}
};
void initshuffle(void){
(void) Py_InitModule("shuffle", ShuffleMethods);
}
在哪一行發生總線錯誤? – ouah
@ouah在執行了一些'printf'動作之後,它看起來像是一直到while循環,並在'while'聲明和/或第一次迭代時失敗。 – jondavidjohn