I'm programming a multi-threaded, simple port scanner to try and familiarize myself with multi-threading, and I've run into a problem. I'm passing a pointer to a struct(Allocated on the heap) as the argument, then dereferencing the pointer in the thread callback and trying to use it to pass info to the thread, such as IP, ports and so on. However, I *think* the threads are segfaulting when it tries to dereference the pointer, but I can't really debug it, as I've never debugged threads and even when I tried doing so with gdb in codeblocks, it seemed to return fine.
The way it 'doesn't work' is basically by not even printing the sPort and ePort variables, or anything else after that, as if it's shut down.
Here's the code:
#define ecs() EnterCriticalSection(&cSection);
#define lcs() LeaveCriticalSection(&cSection);
unsigned int startPort;
unsigned int noPorts;
__stdcall void scanThread(void * Param)
struct sockaddr_in remoteHost;
struct sInfo sinfo = *((struct sInfo*)Param); // Dereferencing the pointer. Wrong ? Cast to struct pointer, dereference pointer?
int sPort = sinfo.startPort,
ePort = sPort + sinfo.noPorts,
printf("Starting port: %d\n", sPort);
remoteHost.sin_family = AF_INET;
if ((remoteHost.sin_addr.s_addr = inet_addr(sinfo.host)) == -1)
printf("Could not resolve host.\n");
memset(remoteHost.sin_zero, 0, 8);
theSocket = socket(AF_INET, SOCK_STREAM, 0);
if (theSocket == INVALID_SOCKET)
printf("Could not create socket: %d\n", WSAGetLastError());
for (; sPort < ePort; sPort++)
remoteHost.sin_port = htons(sPort);
if (connect(theSocket, (struct sockaddr*)&remoteHost, sizeof(struct sockaddr)))
printf("Port %d: CLOSED\n", sPort);
printf("Port %d: OPEN\n", sPort);
int main(int argc, char **argv)
if (argc < 4)
"\tportscanner IP STARTPORT ENDPORT [NO.THREADS]\n\n");
int startPort = atoi(argv), endPort = atoi(argv),
portsPerThread, noThreads = 5, i = 0, x = 0;
if (startPort > endPort)
printf("The start port must be smaller than the end port.\n");
if (argc >= 5) noThreads = atoi(argv);
threadHandles = malloc(noThreads * sizeof(HANDLE));
portsPerThread = ((endPort - startPort)+1) / noThreads;
printf("Number of threads: %d\n"
"Ports per thread: %d\n", noThreads, portsPerThread);
// Array of pointers to struct sInfo.
struct sInfo *scanInfo[noThreads];
for (i = 0; x < noThreads; i += portsPerThread )
// Allocate memory at each pointer.
scanInfo[x] = malloc(sizeof(struct sInfo));
scanInfo[x]->noPorts = portsPerThread;
scanInfo[x]->host = malloc(sizeof(char) * 100);
scanInfo[x]->startPort = i;
threadHandles[x++] = (HANDLE)_beginthreadex(NULL,
(void*)scanInfo[x], // Pass pointer to thread, here. 0,
for(i = 0; i < noThreads; i++)