[C] help with string handling memory leak


 
Thread Tools Search this Thread
Top Forums Programming [C] help with string handling memory leak
# 1  
Old 02-27-2009
Question [C] help with string handling memory leak

Ok, so I've been trying to figure out my fualt in this code for probably a week now.

Hopefully somebody will see what I couldn't see.

Anyways, any help would be greatly appreciated. Lets begin.

Code:
void serverStatus( const char* data )
{
    char* s          ;
    int   i, l = 0   ;
    char* tok        ;
    int   tokcount   ;
    hash_t srv[32]   ;
    bzero(srv, sizeof(srv));

    s = strdup( data+20 );
    strcpy(s, data+20);

    // Tokenize
    for(i = 0, tok = strtok( s, "\\"); tok; tok = strtok( NULL, "\\"))
    {
        l = ( l ? 0 : 1 );
        if( l ) // if its a variable
            strcpy( srv[i].key, tok );

        else    // if its a value
        {
            strcpy( srv[i].val, tok );
            ++i;
        }
    }

    // Dump server info
    tokcount = i;
    i = 0;
    while( i < tokcount )
    {
        if ( strncmp( srv[i].key, SRV_HOSTNAME, strlen(SRV_HOSTNAME) ) == 0 )
        {
            char* tmp = sanitizeString(srv[i].val);
            printf( "%s %s\n", srv[i].key, srv[i].val );
            free(tmp);
        }
        else if ( strncmp( srv[i].key, SRV_MAPNAME,  strlen(SRV_MAPNAME) ) == 0 )
        {
            printf( "%s %s\n", srv[i].key, srv[i].val );
        }        
        ++i;
    }
}

This is my code in question. Although I understand the problem could be prior in my network handling. ( we can explore more on this later. )

So what I know is that the code 'generally', if it does at all, crashes in the while loop.

Freeing my pointer 's' always crashes, ALWAYS. this bothers me a bit.

finally when i do print values, sometimes it prints stuff that isn't supposed to be there. ( ie memory issue )

the hash_t type looks as follows.

Code:
typedef struct info_s {
    char key[256];
    char val[256];
    } hash_t;


none of the values that we tokenize are larger than 255 characters.


Lastly full code is accessible if you would like to see it crash in real time.
( qquery.googlecode.com )


Thanks much for any insight you can provide.
~vroemer
# 2  
Old 02-27-2009
You don't need both strdup and strcpy and since free goes with strdup get rid of the strcpy and the code should be fine. Btw strcpy expects its first argument to be a pointer to an array of char. In your code s is just a pointer to char so there is no room is s to store the string that data+20 points to. So don't even think about keeping strcpy unless s is really char s[1024], that is an array.
# 3  
Old 02-28-2009
Oh, thats interesting I don't remember leaving that there. Thanks for catching that. ok

Ok then, I have a small question to impose onto this then. If I add this to the very end of the function. Why does it cause a memory leak?

Code:
    free(s); 
    s = NULL;

    s = strdup( data+19 );
    while((*s) && (*s != '\n'))
    {
        s++;
    }
    s++; // skip the newline
    printf( "%s", s);
    free(s);


is it because I reasign s? Becuase I reuse data? If always crashes on that final 'free'

valgrind reports, with and without the final free, a loss of the same amount of bytes.


EDIT:
I think I know why, because I moved the pointer right? The fix would be to make an aditional pointer to point at the beginning i believe.
# 4  
Old 02-28-2009
Quote:
Originally Posted by VRoemer
Oh, thats interesting I don't remember leaving that there. Thanks for catching that. ok
I was referring to this code...
Code:
s = strdup( data+20 );  /* don't need both strcpy and strdup */
strcpy(s, data+20);     /* get rid of the strcpy */

Quote:
Originally Posted by VRoemer
Ok then, I have a small question to impose onto this then. If I add this to the very end of the function. Why does it cause a memory leak?

Code:
    free(s); 
    s = NULL;

    s = strdup( data+19 );
    while((*s) && (*s != '\n'))
    {
        s++;
    }
    s++; // skip the newline
    printf( "%s", s);
    free(s);


is it because I reasign s? Becuase I reuse data? If always crashes on that final 'free'

valgrind reports, with and without the final free, a loss of the same amount of bytes.
Yes it's because free expects the exact same pointer that was returned by the call to strdup. By incrementing s you lost the original pointer returned by strdup.
Quote:
Originally Posted by VRoemer
EDIT:
I think I know why, because I moved the pointer right? The fix would be to make an aditional pointer to point at the beginning i believe.
That's right create another pointer that points to the same place as s and increment that one instead of s. This way you won't have any problems when you try to free s.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Web Development

Finding Cause of Memory Leak

Hi We have just got a dedicated server with Fasthosts, O/S is Linux CentOS 6 64 bit. It was a fresh install and I have just moved one WordPress site onto there. The problem is we seem to be getting a memory leak (that's what Fasthosts said) and the database (I think) keeps crashing, so we... (3 Replies)
Discussion started by: Pokeyzx
3 Replies

2. Red Hat

Memory leak

Hi all I am using RED HAT 5.4, and i am getting memory uses problem. when i use "sync;echo 3 > /proc/sys/vm/drop_cache" command the memory will release after 2,3 hour memory show 95%. pls suggest right way. thanks (37 Replies)
Discussion started by: reply.ravi
37 Replies

3. Programming

Memory Leak

Hi, I am trying a database server which keeps a B+ plus tree structure and works on it. I am trying to find the memory used/leak while executing this process. I check the memory leak by using ps uax command. When i execute a delete query i am sure that my code frees up the existing... (9 Replies)
Discussion started by: kumaran_5555
9 Replies

4. IP Networking

memory leak?

Hi All, my client server application can work in two modes: 1) one direction - only client sends msgs to server 2) two directions - server gives 'answers' to client. when program run in the first mode it looks OK, but when server answers to client than client's application exit its... (2 Replies)
Discussion started by: lenna
2 Replies

5. UNIX for Advanced & Expert Users

Need to create a memory leak

Hi. This might be a strange request, but does anyone have any idea on a simple shell script that would use more and more memory as it ran? Like a purposeful leak. I want to test the behaviour of an already running program when the machine runs out of memory. Thanks! (4 Replies)
Discussion started by: rebelbuttmunch
4 Replies

6. Programming

Memory LEAK with pthreads

I have this code... #include <stdio.h> #include <iostream> #include <pthread.h> static void* cliente(void *datos); int main() { pthread_attr_t tattr; int ret; size_t size = PTHREAD_STACK_MIN + 0x0100; ret = pthread_attr_init(&tattr); ret =... (8 Replies)
Discussion started by: JEscola
8 Replies

7. UNIX for Advanced & Expert Users

Check memory leak

I am running c++ code on AIX unix.I have a doubt that my code is using some memory but it is not clearing that.Some time i am getting heap allocation problem.In my code i am not using any malloc,new functions also i am justing using pointers and arrays. Is there any way i can find out if the... (2 Replies)
Discussion started by: ukatru
2 Replies

8. Programming

Memory leak of fork()

Today, I wrote a test code for fork/execvp/waitpid. In the parent process, it fork 100 child processes which only execute "date" to print the current datetime. When any child process die, the parent process will receive a SIGCHLD signal. Then, the parent process will re-fork-execvp the child... (7 Replies)
Discussion started by: whererush
7 Replies

9. Programming

about virtual memory and memory leak

Hi, First of all I appreciate this group very much for its informative discussions and posts. Here is my question. I have one process whose virtual memory size increases linearly from 6MB to 12MB in 20 minutes. Does that mean my process has memory leaks? In what cases does the... (4 Replies)
Discussion started by: shriashishpatil
4 Replies
Login or Register to Ask a Question