使用memcpy

时间:2015-08-26 00:58:49

标签: c segmentation-fault malloc memcpy

我在malloc,指针数组和memcpy方面遇到了一些问题。我有一个名为hex_string的字符串,它总是有一个可被8整除的长度。我试图将这个字符串拆分为子字符串,每个字符串有8个字符。当我在字符串中有16个字符时,这可以正常工作,但如果我将其增加到24个字符以及更高,我会遇到分段错误。任何人都可以帮我解决原因吗?我知道我正在使用很多基本上运行相同循环的for循环,我会压缩这些,但我想分别从程序的每个部分开始。

int main (int argc, char * argv[]) {

    const char * hex_string = "1c0111001f010100abcdef12";
    /* Using this value for hex_string fails - but if the 
    string is replaced with "1c0111001f010100" the program runs fine. */

    int string_length = strlen(hex_string);

    /* get the number of 8 character substrings needed 
    (using ceil to allow me to expand this to arbitrary length strings in the future) */
    int num_of_blocks = (int)ceil((double)string_length / 8); 

    /* allocate memory for pointers to each substring */
    char ** hex_array = (char **) malloc(num_of_blocks * sizeof(char));

    /* allocate 9 bytes for each substring 
    to allow for the 8 characters and the null-terminator. */
    for (int i = 0; i  < num_of_blocks; i++)
        hex_array[i] = (char *) malloc(9);

    /* split the strings into 8-character substrings and add a null-terminator */
    for (int i = 0; i < num_of_blocks; i++) {
            memcpy(hex_array[i], hex_string+(i*8), 8);
            (hex_array[i])[8] = '\0';
    }

    /* print each substring */
    for (int i = 0; i < num_of_blocks; i++)
        printf("substring %d = %s\n",i,hex_array[i]);

    /* free the memory allocated for each substring */
    for (int i = 0; i < num_of_blocks; i++)
        free(hex_array[i]);
    /* free the memory allocated for the pointers to the substrings */
    free(hex_array);

    return 0;
}

1 个答案:

答案 0 :(得分:4)

主要问题是在内存分配中使用了错误的类型 - 常见错误。

// char ** hex_array = (char **) malloc(num_of_blocks * sizeof(char));
char ** hex_array = (char **) malloc(num_of_blocks * sizeof(char *));

@Matt McNabb达成强烈协议后,建议使用以下内容。不需要演员。更容易编码。更易于维护。在这种情况下,不太可能得到错误的类型。

pointer_variable = malloc(n * sizeof *pointer_variable);

char ** hex_array = malloc(num_of_blocks * sizeof *hex_array);