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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can't alloc a two dimensional string array 1

Status
Not open for further replies.

spirou

Programmer
Oct 22, 2001
22
0
0
FR
Can you tell me if the declaration and definition below are correct ?
I had a "segmentation error" after puting some char in the array but I can't find my mistake.

Here is some lines of my code :
Code:
struct t_Zone
{
  short zProfondeur, zLargeur; 
  char **Grille; 
};
typedef struct t_Zone zone;
[\code]
...
[code]
char* initZone(int zProf, int zLarg, zone *t_Zone)
{
  int i;
  char msg[255];
  
  t_Zone->zProfondeur = zProf;
  t_Zone->zLargeur = zLarg;
  
  t_Zone->Grille = calloc(zLarg,1);
  if(t_Zone->Grille == NULL )
  {
    strcpy(msg,"NOT OK");
  }
  else strcpy(msg,"OK");
  
  for( i=0 ; i<zProf && !strcmp(msg,&quot;OK&quot;) ; i++)
  {
    t_Zone->Grille[i] = (char*)calloc(zProf+1,1);
    if(t_Zone->Grille[i] == NULL)
    {
      strcpy(msg,&quot;NOT OK&quot;);
    }
    else strcpy(msg,&quot;OK&quot;);
  }
  return msg;
}
[\code]
 
Hi, 2 things:
1. You cannot return pointer to local a variable from a function.
Code:
return msg;
2. You should use calloc this way:
Code:
calloc( zLarg, sizeof( char* ) );
calloc( zProf+1, sizeof( char ) );
not this way:
Code:
calloc(zLarg,1);
calloc(zProf+1,1);
 
Okay.My program runs correctly.
But it seems returning a pointer from a function like I do, runs corretly too which surprises me.

Thanks a lot.
 
Believe me, you should not EVER do that. (-:
I will try to explain it a bit...
Inside of scopes defined by your function you defined a variable. It was ok. OS ( operation system ) knew that there is a memory space for your variable. After your function ended, OS destroys variable and marks that memory for another use - for another variable. Unfortunatelly you still do have a pointer and you think you can use it. Another variable think it can use it as well...

These bugs are very hard to trace because an error can surprisingly appear on a place no one would expect.
Possible solutions:
dynamic allocation of a variable ( malloc, ... )
or use int, float, ... as a return code. ( not pointers )
Uff... Hope you understand me. X-)
 
I learn this before and I forget it.
Thanks to remember it to me.
 
You can do easy, just add static:
static char msg[255];
This will prevent this string from deleting and you can use it like you programed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top