]> granicus.if.org Git - python/commitdiff
win32_urandom(): There's no need to copy the generated byte string, so
authorTim Peters <tim.peters@gmail.com>
Mon, 30 Aug 2004 17:36:46 +0000 (17:36 +0000)
committerTim Peters <tim.peters@gmail.com>
Mon, 30 Aug 2004 17:36:46 +0000 (17:36 +0000)
don't.

Modules/posixmodule.c

index 3eb1ee8cbcbd84c9fb36f0d28964b4d24f32ef0f..306bce55abd3b88265c9ccffd9ab5a197d653418 100644 (file)
@@ -7239,9 +7239,8 @@ static HCRYPTPROV hCryptProv = 0;
 static PyObject*
 win32_urandom(PyObject *self, PyObject *args)
 {
-       int howMany = 0;
-       unsigned char* bytes = NULL;
-       PyObject* returnVal = NULL;
+       int howMany;
+       PyObject* result;
 
        /* Read arguments */
        if (! PyArg_ParseTuple(args, "i:urandom", &howMany))
@@ -7282,21 +7281,16 @@ win32_urandom(PyObject *self, PyObject *args)
        }
 
        /* Allocate bytes */
-       bytes = (unsigned char*)PyMem_Malloc(howMany);
-       if (bytes == NULL)
-               return PyErr_NoMemory();
-
-       /* Get random data */
-       if (! pCryptGenRandom(hCryptProv, howMany, bytes)) {
-               PyMem_Free(bytes);
-               return win32_error("CryptGenRandom", NULL);
+       result = PyString_FromStringAndSize(NULL, howMany);
+       if (result != NULL) {
+               /* Get random data */
+               if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*)
+                                     PyString_AS_STRING(result))) {
+                       Py_DECREF(result);
+                       return win32_error("CryptGenRandom", NULL);
+               }
        }
-
-       /* Build return value */
-       returnVal = PyString_FromStringAndSize(bytes, howMany);
-       PyMem_Free(bytes);
-
-       return returnVal;
+       return result;
 }
 #endif