-1

I am fairly new to C and have been having a lot of difficulty trying to copy the values of an array of pointers to strings. I have created a struct that contains such a pointer array (part of an implementation of a doubly linked list)

typedef struct Node
{
    int value;
    char *args[41];
    ....
} Node;

When I want to add a node, I have been using the following method

void addNew(char *args[], Node *current)
{
    // first node is passed in, so loop until end of list is reached
    while ((*current).next != NULL
        current = (*current).next;
    // create new node that is linked with the last node
    (*current).next = (Node *)malloc(sizeof(Node));
    ((*current).next)).prev = current;
    current = (*current).next;
    // assign value to new node
    (*current).value = some-new-value;
    // allocate space for new argument array
    (*current).args[41] = (char*)malloc(41 * sizeof(char*));
    int i=0;
    // loop through the arg array and copy each of the passed-in args into the node
    for (i=0; i<41; i++)
        strcpy((*current).args[i], args[i]);
    (*current).next = NULL;
}

I think the root of my problem is in how I am allocating space for the pointers in the new node, but I haven't been able to figure out what I was doing wrong. As it stands, I get a Segmentation Fault (core dumped) as soon as the strcpy line is reached.

Any idea what Im doing wrong?

Kevin Kesicki
  • 155
  • 2
  • 6
  • 18
  • 1
    `(*current).args[41]` is the 42nd element in `(*current).args`, which is an array containing only 41 elements. – user253751 Sep 23 '15 at 03:59
  • [Don't cast malloc in C.](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc) – Iskar Jarak Sep 23 '15 at 04:01

1 Answers1

1

The line

(*current).args[41] = (char*)malloc(41 * sizeof(char*));

does not make sense at all. I am not sure what you were trying to accomplish there. Remove that line.

In order to be able to use:

for (i=0; i<41; i++)
        strcpy((*current).args[i], args[i]);

you need to allocate memory for each element of (*current).args. Here's one way:

for (i=0; i<41; i++)
{
   int len = strlen(args[i]);
   (*current).args[i] = malloc(len+1);
   strcpy((*current).args[i], args[i]);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • that makes sense, i thought the original line was allocating space for the entire array. your solution allocates the space for each pointer individually. thank you for your help, it worked perfectly! – Kevin Kesicki Sep 23 '15 at 04:31