Thread: malloc allocates the same space in the memory

  1. #16
    Registered User
    Join Date
    Apr 2007
    Location
    Greece
    Posts
    52
    Quote Originally Posted by matsp View Post
    Where did you add your printout?
    Exactly after the malloc.

    Quote Originally Posted by matsp View Post
    I can guarantee that if the rest of your code isn't horribly broken, malloc() is allocating memory correctly. Of course, if you overwrite the right bit of memory in the heap (or do a double free, or some other bad thing), you may get a "circular link" in the linked list that malloc()/free() uses to keep track of the memory allocated - and that could of course lead to all sorts of "interesting" effects, including that malloc() itself returns the same value each time.
    What do you mean overwrite the right bit of memory? I simply want it malloc to allocate a different space but it continues to return the same address each time.

    By the way, just re-reading the previous post, are you saying that if you run your application twice, doing a single allocation, you get the same value - that is common and normal. If you call malloc several times within the same process, you should get different values.
    I was thinking that the program gets a random range of addresses each time it runs. Furthermore, the same process calls the malloc and then returns the same address in each iteration in the while loop.

  2. #17
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Well there's nothing wrong with malloc. Try to remove portions of your code (besides the malloc call) to get the minimal code that still has this problem. If you still can't figure out what's wrong, post the trimmed but runnable version of the code here.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #18
    Registered User
    Join Date
    Apr 2007
    Location
    Greece
    Posts
    52
    I tried to do it and the problem was vanished!
    I'll check it again tomorrow because I have to sleep now. It seems crazy. I have just removed some parts of the code that I was considering as unrelated and it worked!!
    I'll post the results in 2 days because I am very busy these days (and exhausted). Thanks for the help.

  4. #19
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I'd say matsp was right about the heap corruption then!
    Maybe you're freeing the same block of memory repeatedly in a loop somewhere earlier, adding it many times to a list of free memory blocks, or something like that...
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #20
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Well, all the evidence indicates that you have messed up the internal data structures that malloc make use of to keep track of which bits of memory are allocated and which are free. Malloc will use a bit of memory just before each memory allocation to track where the "next free" bit of memory is, how large this block is, and some other housekeeping. If you overwrite that housekeeping data with the right values, or as iMalc suggests, free something multiple times, it will cause problems like this.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #21
    Registered User
    Join Date
    Apr 2007
    Location
    Greece
    Posts
    52
    I guess the problem is that I have messed up the internal structures of malloc(). I haven't used free() just to be sure.
    The part of code which works:

    Code:
    /* server program */
    #include <stdio.h>
    #include <stdlib.h>
    
    #define BODY_SIZE 35
    #define LOGIN_SIZE 20
    
    typedef struct user_client {
    
    char login[LOGIN_SIZE];
    
    }client_user;
    
    
    
    // the structure of the mail
    
    typedef struct mail {
    
    client_user sender;
    
    client_user receiver;
    
    char body[BODY_SIZE];
    
    struct mail * next;
    
    } mail;
    
    
    
    // it's actually a pointer to the first element (header) of the structure and then
    
    // each elements points to the next one
    
    typedef mail *mailbox;
    
    
    int main(void)
    {
    	/* initialization */
    	mailbox mail_list; // a pointer to a mail
    	mail specific_message[2];
    	client_user users[2];
    
    	strncpy(users[0].login, "myle", (size_t) LOGIN_SIZE);
    	strncpy(users[1].login, "smyle", (size_t) LOGIN_SIZE);
    
    	// define the senders and the receivers of the mails
    	specific_message[0].sender = users[1];   // user1 has not received any mail
            specific_message[0].receiver = users[0]; // has been sent to user2
            specific_message[1].sender = users[1];
            specific_message[1].receiver = users[0]; // second mail of user2
    
    	strncpy(specific_message[0].body, "lalalalalalalala", (size_t) BODY_SIZE);
    	strncpy(specific_message[1].body, "ta tarata tarata ta ta", (size_t) BODY_SIZE);
    
    	// each maillist contains one mail only
    	specific_message[0].next = &specific_message[1];
    	specific_message[1].next = NULL;
    	
    	mail_list = &specific_message[0];
    	/* end of initialization */
    
    	/* the actual code begins here */
    	int i = 0;
    	for (i = 0; i < 4; i ++) // the server waits for new connections
    	{
    	printf("Iteration: %d\n", i);
    	mailbox sent_mail;
    	sent_mail = malloc(sizeof(mail));
    	// Debugging
    	//printf("The pointer value is: %x\n",sent_mail);
    	//printf("The address of the pointer  is: %x\n", &sent_mail);
    	// if malloc fails
    	if (sent_mail==NULL){
    		printf("You don't have enough memory on your system. This application is going to be killed\n");
    		exit(1);
    	}
    	// the +1 in strlen is because of the 1 extra position required for the '\0' character
    	strncpy(sent_mail->sender.login, "something1", strlen("something1") + 1);
    	strncpy(sent_mail->receiver.login, "something2", strlen("something2") + 1);
    	strncpy(sent_mail->body, "something3", strlen("something3") + 1);
    
    	// the newest mail is the first one
    	sent_mail->next = mail_list;
    	mail_list = sent_mail;
    
    	// print all the mail of this user
    	mailbox next_mail = mail_list;
    	while(next_mail != NULL)
    	{
    		printf("%s user has received the mail\nbody = %s \n by %s\n\n", next_mail->receiver.login, next_mail->body,
    		next_mail->sender.login);
    		next_mail = next_mail->next;
    	}
    }// end of loop	
    	printf("Exit\n");
    	return 0;
    }
    but If I put it with the rest of my code, the problem makes its appearance.

  7. #22
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    So you need to figure out where you are messing with the data outside your allocated range. As a rough hack, you could try doubling the size for one malloc() at a time until you see the problem go away.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #23
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    1. Learn how to indent code.
    Code:
    /* server program */
    #include <stdio.h>
    #include <stdlib.h>
    
    #define BODY_SIZE 35
    #define LOGIN_SIZE 20
    
    typedef struct user_client {
        char login[LOGIN_SIZE];
    } client_user;
    
    // the structure of the mail
    typedef struct mail {
        client_user sender;
        client_user receiver;
        char body[BODY_SIZE];
        struct mail *next;
    } mail;
    
    // it's actually a pointer to the first element (header) of the structure and then
    // each elements points to the next one
    typedef mail *mailbox;
    
    int main(void)
    {
        /* initialization */
        mailbox mail_list;          // a pointer to a mail
        mail specific_message[2];
        client_user users[2];
    
        strncpy(users[0].login, "myle", (size_t) LOGIN_SIZE);
        strncpy(users[1].login, "smyle", (size_t) LOGIN_SIZE);
    
        // define the senders and the receivers of the mails
        specific_message[0].sender = users[1];  // user1 has not received any mail
        specific_message[0].receiver = users[0];  // has been sent to user2
        specific_message[1].sender = users[1];
        specific_message[1].receiver = users[0];  // second mail of user2
    
        strncpy(specific_message[0].body, "lalalalalalalala",
                (size_t) BODY_SIZE);
        strncpy(specific_message[1].body, "ta tarata tarata ta ta",
                (size_t) BODY_SIZE);
    
        // each maillist contains one mail only
        specific_message[0].next = &specific_message[1];
        specific_message[1].next = NULL;
    
        mail_list = &specific_message[0];
        /* end of initialization */
    
        /* the actual code begins here */
        int i = 0;
        for (i = 0; i < 4; i++)     // the server waits for new connections
        {
            printf("Iteration: &#37;d\n", i);
            mailbox sent_mail;
            sent_mail = malloc(sizeof(mail));
            // Debugging
            //printf("The pointer value is: %x\n",sent_mail);
            //printf("The address of the pointer  is: %x\n", &sent_mail);
            // if malloc fails
            if (sent_mail == NULL) {
                printf
                    ("You don't have enough memory on your system. This application is going to be killed\n");
                exit(1);
            }
    
            // the +1 in strlen is because of the 1 extra position required for the '\0' character
            strncpy(sent_mail->sender.login, "something1", strlen("something1") + 1);
            strncpy(sent_mail->receiver.login, "something2", strlen("something2") + 1);
            strncpy(sent_mail->body, "something3", strlen("something3") + 1);
    
            // the newest mail is the first one
            sent_mail->next = mail_list;
            mail_list = sent_mail;
    
            // print all the mail of this user
            mailbox next_mail = mail_list;
            while (next_mail != NULL) {
                printf("%s user has received the mail\nbody = %s \n by %s\n\n",
                       next_mail->receiver.login, next_mail->body,
                       next_mail->sender.login);
                next_mail = next_mail->next;
            }
        }                           // end of loop 
        printf("Exit\n");
        return 0;
    }
    2. typedef mail *mailbox;
    This is all but a useless typedef IMO.
    Knowing how many levels of indirection are really present on any given variable is best answered simply by looking at the declaration and counting the asterisks. Rummaging through a series of typedefs doesn't help.

    3. sent_mail = malloc(sizeof(mail));
    When do you set send_mail->next to NULL ?
    Or more accurately since you're always appending to the head of the list, set
    mailbox mail_list = NULL;

    Your while loop never stops in the right place, and instead marches off through memory.

    4. You have a lot of mixed declarations and statements, which are not legal in C89 code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #24
    Registered User
    Join Date
    Apr 2007
    Location
    Greece
    Posts
    52
    ...I figure out where my problem was. I was calling fork() but I didn't kill the child process in any case, so sometimes it was still alive and memory was messed up. The problem was solved when I took care of it.

    @Salem: Thanks for pointing out my mistakes. The wrong intended is because I was in hurry.
    About the mailbox, you are right, it isn't needed and may confuse someone.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with insert/delete binary search tree
    By Nazgulled in forum C Programming
    Replies: 39
    Last Post: 03-25-2009, 04:24 PM
  2. memory problem, maybe malloc struct...
    By s_siouris in forum C Programming
    Replies: 3
    Last Post: 07-11-2008, 08:34 AM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-13-2001, 09:57 AM