malloc vs realloc


 
Thread Tools Search this Thread
Top Forums Programming malloc vs realloc
# 1  
Old 03-17-2010
malloc vs realloc

Why when using realloc, john is reversed 3 times but not the other 2 names ? But if I use malloc, then the 3 names are reversed correctly ? (but then there is a memory leak)

How can I reverse all 3 names without a memory leak ?

Code:
char *BUFFER = NULL;

char *STRREVERSE(const char *STRING)
{
	BUFFER = (char *)realloc(BUFFER, strlen(STRING) + 1);

	size_t COUNT = 0;
	size_t LENGTH = strlen(STRING) - 1;

	while(COUNT <= LENGTH)
	{
		BUFFER[COUNT] = STRING[LENGTH - COUNT];

		COUNT++;
	}

	BUFFER[COUNT] = '\0';

	return BUFFER;
}

int main(void)
{
	printf("%s\n%s\n%s\n", STRREVERSE("john"), STRREVERSE("jack"), STRREVERSE("jill"));

	return 0;
}


Last edited by cyler; 03-17-2010 at 04:58 PM..
# 2  
Old 03-17-2010
Code:
#include <string.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char *
strrev(char *src)
{
   char *p=src;
   char *q=strchr(src,'\0');
   char tmp=0x0;
   
   for(q--; q>p; q--,p++)
   {
      tmp=*q;
      *q=*p;
      *p=tmp;
   }
   return src;
}


int main()
{
    char one[12]={0x0};
    char two[12]={0x0};
    char three[12]={0x0};
    strcpy(one, "jack");
    strcpy(two, "jill");
    strcpy(three, "john");
    printf("%s\t %s\t  %s\n", strrev(one), strrev(two), strrev(three));
}

The way you set up your code, you were sending const strings to the reverser.
You had to call something like strdup() - automagic way to duplicate strings - or malloc or realloc.

In that case: You need to have separate objects for each call to strrev. The objects have to be created in the calling routine not the strrev routine. This is because you called all three in one function call to printf().

You also could have used printf() free() printf() free().. using your malloc code.

---------- Post updated at 20:45 ---------- Previous update was at 18:36 ----------

Revisiting this: you may want to read up on the concept of a sequence point in C.
http://www.open-std.org/jtc1/sc22/wg...docs/n1124.pdf
# 3  
Old 03-18-2010
I have just modified the single line in your program.
Try with the following code.
Code:
char *STRREVERSE(const char *STRING)
{
        char *BUFFER = NULL;
        BUFFER = (char *)realloc(BUFFER, strlen(STRING) + 1);

        size_t COUNT = 0;
        size_t LENGTH = strlen(STRING) - 1;

        while(COUNT <= LENGTH)
        {
                BUFFER[COUNT] = STRING[LENGTH - COUNT];

                COUNT++;
        }

        BUFFER[COUNT] = '\0';

        return BUFFER;
}

int main(void)
{
        printf("%s\n%s\n%s\n", STRREVERSE("john"), STRREVERSE("jack"), STRREVERSE("jill"));

        return 0;
}

In your program you have declared the char pointer BUFFER as a global pointer.
And you are calling the function in printf().
printf() is right associative.So STRREVERSE("jill") will be called first then STRREVERSE("jack") then STRREVERSE("john").
So finally the pointer BUFFER will have the reversed string of john only.
And The function STRREVERSE is returning char pointer(char *).
So the return value of the three function calls will be pointing the same address.(address of BUFFER).
BUFFER contains reversed string of john only.
So the value "nhoj" will get printed for three times.
So I have declared the BUFFER as a local pointer.

Last edited by kiruthika_sri; 03-18-2010 at 01:34 AM..
# 4  
Old 03-18-2010
Quote:
Originally Posted by kiruthika_sri
I have just modified the single line in your program.
Try with the following code.
According to Valgrind, your code has a memory leak:
Code:
==31733== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 8 from 1)
==31733== malloc/free: in use at exit: 15 bytes in 3 blocks.
==31733== malloc/free: 3 allocs, 0 frees, 15 bytes allocated.


Last edited by cyler; 03-18-2010 at 07:05 AM..
# 5  
Old 03-18-2010
Consider sequence points, which are really your problem in your code - how to know when an operation will take place.
http://www.open-std.org/jtc1/sc22/wg...docs/n1124.pdf
# 6  
Old 03-18-2010
Quote:
Originally Posted by kiruthika_sri
printf() is right associative.So STRREVERSE("jill") will be called first then STRREVERSE("jack") then STRREVERSE("john").
Ah really? Unless I am mistaken, the ANSI-C standard leaves the order of parameters evaluation up to the compiler ("it's unspecified"). This can be left-to-right, or right-to-left or anything else the compiler may find convenient.

Cheers,
Loïc.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

problem with realloc( i think is gcc :/ )

Hi everyone, i made this program. is a simple one for practising malloc, realloc and structs. I have a struct named shop as global variable in which i take the size of the matrix from the keyboard and after i malloc it. I insert the values with the fullarray() and after i print the matrix with... (7 Replies)
Discussion started by: giampoul
7 Replies

2. UNIX for Dummies Questions & Answers

about realloc routing

#include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int* allocat_array(void) { int *array; int tmp; int n_values = 0 ; array = malloc(sizeof(int)); if(array == NULL) return NULL; while(scanf("%d",&tmp) != EOF) { ... (1 Reply)
Discussion started by: vincent__tse
1 Replies

3. Programming

realloc() fails

Not sure in which forum to post this. I'm trying here, in Programming. I'm working on a PC with Intel Duo processor & 2GB of ram. OS is Ubuntu 10.04. I'm having problems with a C++ program that makes extensive use of realloc(). It happens that as soon as the overall memory allocated(OS +... (14 Replies)
Discussion started by: mamboknave
14 Replies

4. Programming

Realloc() question

b = realloc(a, 1000); if realloc succeeds and b!=a (not in-place replacement), does realloc automatically free a or I should free both a and b afterwards? thank you! (5 Replies)
Discussion started by: bashuser2
5 Replies

5. Programming

realloc fails in C : what next ?

Hi all I'm trying to use someone else's software, which has a realloc that fails in it. This is probably due to memory limitations, as it only happens when I use this software on huge datasets. First question : how to diagnose if it's a soft or hard limitation? I mean, if it's due to my... (10 Replies)
Discussion started by: jossojjos
10 Replies

6. Programming

What happens when realloc() fails?

Hi, I am seeing varying results about, when realloc() fails in reallocation. Which one is correct out of the below? a) realloc() maintains the original pointer (i.e) the original pointer is left unaltered/untouched but relloc() returns the NULL value. b) original buffer pointer is lost... (3 Replies)
Discussion started by: royalibrahim
3 Replies

7. Programming

tolower (static pointer + malloc + realloc)

N00B here. This function would be easier using a char pointer along with free. But I wish to learn how to use char static pointers (they do not require free, right ?). How do I erase the content of a static pointer ? Terminating the string works but the static pointer's content is not being... (4 Replies)
Discussion started by: limmer
4 Replies

8. Programming

help with realloc() on Linux

hi, I'm using gcc version 3.4.6 on a Red Hat system... (not sure how to determine version of glibc) when i run the following, i get: glibc detected *** realloc(): invalid next size: 0x0804a170 I'm not sure what is wrong. The error happens on the second iteration of the while loop.... (3 Replies)
Discussion started by: Andrewkl
3 Replies

9. Programming

Does realloc free fairly?

Hello, my program works properly but valgrind tells me I am not freeing allocated memory. I think the problem is in realloc. I am pretty sure I do something wrong with realloc, because I changed it a bit and valgrind noticed less errors (that the program wasn't working properly with less errors... (3 Replies)
Discussion started by: samciz
3 Replies

10. Programming

Realloc

Can Any body give me a exampla which has the usage of realloc i want a function which uses realloc & increases /decreases the size of a pointer (0 Replies)
Discussion started by: wojtyla
0 Replies
Login or Register to Ask a Question