Jump to content

[C] Strange problem with variables


Recommended Posts

I have to make a process management system using threads and such for uni, and I've got a very strange error, when i create a thread the label of the last thread changes as well...hard to explain, ill post the code that i think is causing the problem

Header stuff

#define NTHREADS 10

pthread_t threads[NTHREADS];

char* threadLabels[NTHREADS];

int numThreads = 0;

This is the function that creates the threads.

void createThread( char* label)

{

    if ( numThreads < NTHREADS )

    {

        trim(label);

        printf("Creating new thread (%s)\tthreadNo: %d\n", label, numThreads);

        threadLabels[numThreads]= label;

        pthread_create(&threads[numThreads], NULL, (void*)&process, (void*)NULL);

        numThreads++;

    }

    else

    {

        printf("Maximum number of threads reached");

    }

}

and this is the output

jake@linux:~/Desktop/spd> ./a.out

Command: >new thread1

Creating new thread (thread1)  threadNo: 0

Command: >ms

Thread No      Process Label

0              thread1

Total Number threads:  1

Command: >new thread2

Creating new thread (thread2)  threadNo: 1

Command: >ms

Thread No      Process Label

0              thread2

1              thread2

Total Number threads:  2

Command: >

Any help would be greatly appreciated, im not that good with c, and its prolly something really stupid, but i just cant figure it out

Link to comment
Share on other sites


  • 2 weeks later...

You didn't post enough code, but I suspect the problem is here:

void createThread( char* label)

What is filling in the parameter "label"? Where does the string memory come from?

You are storing the pointer in permanently in threadLabels. Make sure that memory pointed to has at least a long a lifetime as it is pointed to by threadLabels. Failure to do this could lead to bugs like you are seeing as well as crashes.

Also, you had better hope that trim() does not write beyond the length of the string passed in as that could be disasterous.

May I suggest including the <string> header and using std::string which automatically contains and manages each string's memory.

Hope this helps.

Edited by azagahl
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...