as3rdaccount
as3rdaccount

Reputation: 3941

memory allocation for pointers in c

I have an array as follows:

 char* arg[1024];

Now to initialize arg which I will be passing to a function I am doing the following:

 arg = (char**)calloc(1024,sizeof(char*)); 

However whenever I pass arg to the function. I end up getting a segmentation fault. The function is basically doing some very simple command to word parsing:

 void parse(char* buffer, char** arg)
 {
   while(*buffer!='\0')
   {
     *arg=buffer;
      arg++;
      while(*buffer!=' ')
      buffer++;

      while(*buffer == ' ')
      {
         *buffer = '\0';
          buffer++;
      }         

   }
 }

Am I doing something wrong in memory allocation? or passing pointers?

Upvotes: 0

Views: 150

Answers (3)

Daij-Djan
Daij-Djan

Reputation: 50089

arg is already allocated in your case. you say you need it to be 1024 elements big -- its statically allocated

=> leave the out the char *arg[1024] and replace it with char **arg

Upvotes: 1

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

char* arg[1024]; is array of char pointers.

arg = (char**)calloc(1024,sizeof(char*)); is wrong. We can't assign new allocated memory address to arg.

if you want to create array of strings then do like this: (I think you need this)

char* arg[1024];
arg[i] = (char*)calloc(1024,sizeof(char)); 

where i is an index.

You says segmentation fault. but I think you should get an compilation error for arg = (char**)calloc(1024,sizeof(char*)); statement. error: incompatible types when assigning

I also noticed errors in parse(). (answered by Veger)
You can also use strsep() function for parsing you buffer string, here my answer can be useful for this purpose.

Upvotes: 1

Veger
Veger

Reputation: 37905

char* arg[1024];

provides a statically allocated array of 1024 char pointers. You do not need to allocate it dynamical again. So remove your calloc() line.

Besides your allocation problem there is another bug. Take a look at:

while(*buffer != ' ')
    buffer++;

What happens if buffer = "test"? Your while-loop will not find a space and continues to iterate outside buffer. Resulting in all kinds of undefined behavior...

To fix it you need to check for the string terminator as well:

while(*buffer != 0 && *buffer != ' ')
    buffer++;

Upvotes: 4

Related Questions