Thread: free needed or not?

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    77

    free needed or not?

    hi every1,
    I use not-blocked tcp socket and i needed help with that..

    Code:
    write(sock, (struct auth*)&autorization, sizeof(struct auth));
    r = read(socket_fd, recv, sizeof(recv));
    	for (i = 0; i < r; ++i){
    		if (.. /*checkout recv*/...){
                                   write(sock, &data, sizeof(data));
    		}else{
    		printf("Authentication fault\n");
    		goto exit;
    		}
    	}
    free(recv); // 1
    r = read(socket_fd, recv, sizeof(recv));
    // todo  smth...
    1) it's free needed or not? Because in the next if autorization was succesfull, that should do something.

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    Was recv returned to you from a call to malloc()? If so, yes. If it wasn't, then you probably shouldn't be calling free() on it.

    Also, will free() be called if the goto exit is taken?
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Is this a trick question?

    Quote Originally Posted by quantt View Post
    free(recv); // 1
    r = read(socket_fd, recv, sizeof(recv));
    Since read() does not allocate space, if recv is a pointer, this cannot be good. No you should not use free() there. Why do you want to?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Not to mention that if you are using sizeof(recv) in your code, chances are recv was not returned by malloc at all, and thus you do not need to free it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. free() doesn't seem to work...
    By AlienJedi in forum C Programming
    Replies: 10
    Last Post: 01-29-2008, 05:27 PM
  2. Free Store of memory
    By George2 in forum C++ Programming
    Replies: 6
    Last Post: 11-12-2007, 02:27 PM
  3. Pointer's
    By xlordt in forum C Programming
    Replies: 13
    Last Post: 10-14-2003, 02:15 PM