Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack dump when copy characters to an array of char pointers

Tags:

c

pointers

gcc 4.4.3 c89

I have the following source file.

However, I get a stack dump on the following line:

printf("dest: %d [ %s ]\n", i, dest[i]);

The reason is that if fails to break from the for loop. I have tried different conditions in the for loop to try and break before printing.

i != NULL
i != '\0'
i != 0

However, all of the above fails to work. I could use the sizeof(src) as a condition. But I just want to know why I am getting this stack dump using my current method.

When I check using gdb all the array elements have been initialized to nul:

(gdb) p dest
$8 = {0x0 <repeats 11 times>}

source code:

void copy_characters()
{
    /* static character array */
    char src[] = "sourcefile";
    /* array of pointers to char */
    char *dest[sizeof(src)] = {0};
    size_t i = 0;

    /* Display the source characters */
    for(i = 0; src[i] != '\0'; i++) {
        printf("src [ %c ]\n", src[i]);
    }

    /* Copy the characters */
    for(i = 0; i < sizeof(src); i++) {
        dest[i] = &src[i];
    }

    /* Display them */
    for(i = 0; dest[i] != '\0'; i++) {
        printf("dest: %d [ %s ]\n", i, dest[i]);
    }
}

Many thanks for any suggestions,

like image 277
ant2009 Avatar asked Dec 12 '25 07:12

ant2009


1 Answers

First off - I'm not sure what you're trying to do here. But:

dest[i] is a pointer pointing to a character.

You should test if the value pointed by dest[i] is null, as:

for(i = 0; *(dest[i]) != '\0'; i++) {
like image 69
adamk Avatar answered Dec 15 '25 02:12

adamk