Solved

free() behaviour questions

Posted on 2004-10-17
19
202 Views
Last Modified: 2010-04-15
OK, I have a unix shell. I am using gcc compiler for cygwin and on a unix box @ uni.

I am wondering why, if I have the shell's control loop only exiting when 'exit' is typed in to the command line, a bunch of free()s that shouldn't have even been reached cause segmentation faults before the shell script has exited. The free()s relate to the input string and this is the problem, I beleive. The free()s are before a return of the regular int on exiting the main function.

Whatchya reckon?? Guidance appreciated.
0
Comment
Question by:Mindbender
  • 9
  • 5
  • 4
  • +1
19 Comments
 
LVL 1

Author Comment

by:Mindbender
ID: 12333203
And an extra 50 points to the person that can tell me how to get the login name into a C program - like getting logname into a string so I can print it.
0
 
LVL 11

Assisted Solution

by:avizit
avizit earned 50 total points
ID: 12333320
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12333334
Ahh, thanks! Why isn't that referenced by the getdomainname man page I wonder?
0
 
LVL 12

Expert Comment

by:stefan73
ID: 12337881
Hi Mindbender,
> get the login name into a C program
You could also use the environment for that:
getenv("USER")

>Why isn't that referenced by the getdomainname man page I wonder?
Because everything's related ... somehow.

Cheers!

Stefan
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12344643
Why does the free() cause segmentation faults before they're processed??

Code example

char* function() {
    char* stringA = (char*)malloc(MAX_STRING);
    char* stringB = (char*)malloc(MAX_STRING);
    char* stringC = (char*)malloc(2*MAX_STRING);

    stringA = "something";
    stringB = "somethingelse";
    stringC = strcat(stringA,stringB);

    free(stringA);
    free(stringB);

    return(stringC);
}

Why doesn't that work?
0
 
LVL 11

Expert Comment

by:avizit
ID: 12344863
one problem with this ( which may or may not be related to yours segfault)


strcat doesnt concatenate two strings and return the result ,

its appends the second argument to the first ....


man strcat NAME
       strcat, strncat - concatenate two strings

SYNOPSIS
       #include <string.h>

       char *strcat(char *dest, const char *src);

       char *strncat(char *dest, const char *src, size_t n);

DESCRIPTION
       The  strcat()  function  appends the src string to the dest string overwriting the `\0' character at the end of dest, and
       then adds a terminating `\0' character.  The strings may not overlap, and the dest string must have enough space for  the
       result.

       The strncat() function is similar, except that only the first n characters of src are appended to dest.

RETURN VALUE
       The strcat() and strncat() functions return a pointer to the resulting string dest.



0
 
LVL 1

Author Comment

by:Mindbender
ID: 12344923
OK, that's true, but that is just because I was too lazy to properly write it out ;) Sorry. I was intending to purely demonstrate the way I had used free() calls. If the free calls are put after the return, it all works fine.

The issue here is that I am inexperienced with C....can I put return() anywhere in a function and have it still work? That would explain it well enough for me. I am used to putting return as the last statement in a function. There is no set text for this unit, so I went without.
0
 
LVL 8

Accepted Solution

by:
ssnkumar earned 125 total points
ID: 12344937
In your code you are assigning memory by:
    char* stringA = (char*)malloc(MAX_STRING);
After the above statement, stringA should have a valid address, where you can write to.

With the statement:
    stringA = "something";
you are changing the address of straingA to some address where the string literal "something" will be stored!
This address is not assigned by you using malloc. So, you cannot also free this address.
That is the reason:
    free(stringA);
gives a segmentation fault!

To overcome this error, you have to change:
    stringA = "something";
to:
    strcpy(stringA, "something");
This will copy the string "something" to stringA.
Now the address of stringA is not changing. It still has the address got after calling malloc. So, you can free it.

After these changes your code becomes:
char* function() {
    char* stringA = (char*)malloc(MAX_STRING);
    char* stringB = (char*)malloc(MAX_STRING);
    char* stringC = (char*)malloc(2*MAX_STRING);

    strcpy(stringA, "something");
    strcpy(stringB, "somethingelse");
    strcpy(stringC, stringA);
    strcat(stringC, stringB);

    free(stringA);
    free(stringB);

    return(stringC);
}

Hope this helps......

-ssnkumar
0
 
LVL 11

Expert Comment

by:avizit
ID: 12344941
anything after return in a fucntion is not executed ..
return , just returns the control to the function caller

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Expert Comment

by:ssnkumar
ID: 12344943
>....can I put return() anywhere in a function and have it still work?
When the execution encounters "return" statement, it will return from the function at that point.
The subsequent statements will not executed!
That's the reason your code worked when you moved "return" to before "free"!
Actually the "free" statements nver got executed and hence it didn't crash!!

-ssnkumar
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12344974
I guess I should try it, eh? The reason I am not is because I am in a Winblows lab right now using Java (no unix access unless I feel like SSH'ing nutmeg), but I will. If I answer my own question, what do I do? I want to give points to avizit, but it isn't the correct answer for the main question. Been a LONG time since I have been here (about year in a serious sense).

0
 
LVL 1

Author Comment

by:Mindbender
ID: 12344978
OK then, but why did the free() statements cause segmentation faults?
0
 
LVL 11

Expert Comment

by:avizit
ID: 12344990
free() can only free what has been allocated by malloc etc ,
free cannot free just any pointers ..

so when you have some other value in stringA which has not be allocated by malloc/calloc etc you get segfault
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12344992
Wow, I can't keep up with you guys. OK, thankyou, that explains my problems. Let me try it out and I will award points.

0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 12344993
Look at my first comment:
>This address is not assigned by you using malloc. So, you cannot also free this address.
>That is the reason:
>    free(stringA);
>gives a segmentation fault!

Hope this helps you.....

-ssnkumar
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 12344999
Hi Mindbender,

   If you had read my first comment, it would have become clear for you.
   I have clearly explained what is happening with your code. Why it segfaults and also how to overcome it.
   I don't know if you checked it.

-ssnkumar
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12345004
Christ, what a mess. To clarify my responses:

I will probably accept a split answer, 125 to ssnkumar, 50 to avizit.

I have been flicking between apps, and not paying a large amount of attention to this page. I completely missed ssnkumar's explanation, which I will probably accept as an answer.
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 12345010
Thanks for reading my comments also.
I didn't bargain for the points!
I felt bad that, you completely missed out my comments.

Happy to know that it helped you:-)

-ssnkumar
0
 
LVL 1

Author Comment

by:Mindbender
ID: 12345107
Thanks guys, points awarded!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now