Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Program using realloc on global variable

Status
Not open for further replies.

chigley

Programmer
Sep 30, 2002
104
GB
Hi,

I have a struct which is defined in a header file (firewallrules.h) thus

Code:
typedef struct _FirewallRule FirewallRule;
struct _FirewallRule{
		char * dnsValue;
		char * ipAddress;
		int protocol;
		char * user;
		char * group;
		int action;
		int ruleStatus;
};

typedef struct _Program Program;
struct _Program{
	int 	id;
	char * 	path;
	char * 	name;
	FirewallRule * firewallRules;
};

It is declared as global thus

Code:
extern Program * programs;
extern int lNumPrograms;

and defined in a C file thus

Program * programs = NULL;
int lNumPrograms=0;

I have a file called programsearch.c that includes firewallrules.h

It has a routine called addProgram which adds a Program item to the Programs array.

Code:
void addProgram(char * name, char * path)
{
	Program newProgram;
	printf("Adding program %d %s \n", lNumPrograms ,name);
	newProgram.id=lNumPrograms;
	strcpy(newProgram.name,name);
	strcpy(newProgram.path,path);
	newProgram.firewallRules = NULL;
	programs = (Program*)realloc(programs, (lNumPrograms + 1) * (sizeof(Program)));
    programs[lNumPrograms] = newProgram;
    lNumPrograms++;
	
	return;
}

It used to work beatifully when the _Program struct was declared in the programsearch.h file but since I have moved it and declared it using the extern keyword I have been getting some erratic behaviour.

It does work, but only for the first 19 times it is called, then it blows up.

Can someone give me some idea as to what the problem might be, and how to go about tracking it down.

Charlie Benger-Stevenson
Hart Hill IT Ltd
 
Try
Code:
Program newProgram = { 0 };

Well, not really.
But it should demonstrate the reason by blowing up on the first call, and not blowing up at some random point in the future, because of a seemingly unrelated change.

The answer is of course that you're not allocating any space for your name and path members.

> programs = (Program*)realloc(programs, (lNumPrograms + 1) * (sizeof(Program)));
This is unsafe. If realloc returns NULL, then you've leaked your old memory.
Use
Code:
void *temp = realloc(programs, (lNumPrograms + 1) * (sizeof(Program)));
if ( temp != NULL ) {
  programs = temp;
} else {
  // do something with programs, which is still valid
  // as if realloc was never called.
  // eg. save and exit, or popup 'no more programs'
}


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top