1833491 Members
2865 Online
110052 Solutions
New Discussion

C question

 
SOLVED
Go to solution
Ridzuan Zakaria
Frequent Advisor

C question

Hi

I have moved my C program from HP-UX 11.11 to Linux AS release 3 environment. I can recompiled the code on Linux successfully but I got memory dump error when try to run the executable. The problem is caused by free() function I used deallocate memory in the code. This is my gcc compiler version.

"Reading specs from /usr/lib/gcc-lib/i386-redhat-linux7/2.96/specs
gcc version 2.96 20000731 (Red Hat Linux 7.3 2.96-123)"

When I check the manpage for "free" on Linux return a different function (free - display information about free and used memory on the system).

How do I deallocate memory on Linux platfrom?

Thanks.
quest for perfections
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: C question

Man free returns the first "hit" it finds unless you specify a section. Man 3 free should display the function for you. Now for the bad news, free works just the same on both platforms. I suspect that you are trying to free a chunk of memory that was not allocated by malloc, calloc, et al or you are trying to free the same chunk of memory more than once.

If it ain't broke, I can fix that.
Ridzuan Zakaria
Frequent Advisor

Re: C question

Hi Clay,

I am using getpwuid function and assuming it uses malloc(). Maybe I am wrong. The code with free() work just fine on HP-UX.

Thanks.
quest for perfections
Ridzuan Zakaria
Frequent Advisor

Re: C question

Hi,

This is my code.

sessionid = (struct passwd*)getpwuid(getuid());
if (sessionid != NULL)
{
strcpy(user,sessionid->pw_name);
free(sessionid);
}

Thanks.
quest for perfections
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: C question

Ah, there's your problem (and it's working by accident on HP-UX). getpwuid returns either a NULL (on failure) or a pointer to a static address so that repeated invocations of getpwuid return the same address. The value returned shound NEVER be freed because it was never malloc'ed.
If it ain't broke, I can fix that.
Ridzuan Zakaria
Frequent Advisor

Re: C question

Thanks Clay.
quest for perfections
H.Merijn Brand (procura
Honored Contributor

Re: C question

Better yet, where possible, use the re-entrant versions of those functions. They do the same, but are much safer:

--8<---
The getpwnam_r () and getpwuid_r () functions find the same
information, but store the retrieved passwd structure in
the space pointed to by pwbuf. This passwd structure con-
tains pointers to strings, and these strings are stored in
the buffer buf of size buflen. A pointer to the result
(in case of success) or NULL (in case no entry was found
or an error occurred) is stored in *pwbufp.
-->8---

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn