[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 178
  • Last Modified:

100pt question malloc()

Here is the question for 100 pts! help :)
  • 3
1 Solution

I looked at your code and you are freeing the code malloced code, but
I suspect that this is not what you intended to do.
The problem is that all that you are doing is simply freeing memory.
For example, your code there are the following three lines:

   printf("Before free %s --- ", tbp->entry[j].name);
   printf("After free %s\n", tbp->entry[j].name);

The first line is OK assuming that you do not have a null pointer.
The second line is ok because the memory was malloced.
The third line is WRONG because you printed memory that you just deleted.
What you really want to do is to swap the names.
I assume that nothing else points to the memory so you could do this as follows:

for(i=0; i < n; i++) {
   for(j=0; j< n-1; j++) {
      if(strcmp(tbp->entry[j].name, tbp->entry[j+1].name) > 0) {
         // switch names
         char* temp = tbp->entry[j].name;
         tbp->entry[j].name = tbp->entry[j+1].name;
         tbp->entry[j+1].name = temp;
         // switch the phone numbers
         temp = tbp->entry[j].telNum;
         tbp->entry[j].name = tbp->entry[j+1].telNum;
         tbp->entry[j+1].telNum = temp;

I agree your answer, pitonyak
ciskAuthor Commented:
Adjusted points from 0 to 50
ciskAuthor Commented:
Comment accepted as answer
ciskAuthor Commented:
I'm sorry but i canceled this question a long time ago and i guess i thought it was going to delete this one too.. i figured out why a few minutes after i pointed..

 BUT i'm going to ago ahead and ive 50 points to pitonyak because he was right and he answered in 2 hours

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now