The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> C Programming
|
What happens when realloc fails?
Discuss What happens when realloc fails? in the C Programming forum on Dev Shed. What happens when realloc fails? C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

February 21st, 2013, 12:42 PM
|
|
Contributing User
|
|
Join Date: Nov 2012
Posts: 112
Time spent in forums: 1 Day 4 h 12 m 48 sec
Reputation Power: 1
|
|
|
What happens when realloc fails?
what happens if realloc fails to allocate new memory?
does it return NULL?
if so, can i lose data?
for example, consider the following code:
Code:
int main()
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(8);
strcpy(str, "example");
printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 5);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
(it's not my code, i found it on the internet)
now lets say realloc fails and returns NULL, does it mean i'll lose the address of "example" for good?
|

February 21st, 2013, 12:59 PM
|
 |
Contributed User
|
|
|
|
Yes, that code is broken (twice).
First mistake is that the realloc size is new new total size, not the amount you want to add to the old size. So realloc'ing down to 5 bytes would be completely wrong.
The other problem is detecting and handling the error case.
What you should do is this.
Code:
void *temp = realloc(str, 12);
if ( temp != NULL ) {
str = temp;
strcat(str, ".com");
} else {
// no more memory:
// str is still valid, so do something with it
// if this were an editor say, you might try to save a recovery file.
free( str );
}
|

February 21st, 2013, 02:29 PM
|
|
Contributing User
|
|
Join Date: Nov 2012
Posts: 112
Time spent in forums: 1 Day 4 h 12 m 48 sec
Reputation Power: 1
|
|
|
thank you so much, salem.
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|