代码之家  ›  专栏  ›  技术社区  ›  andrew1601

使用memcpy〔closed〕获取分段错误

  •  0
  • andrew1601  · 技术社区  · 9 年前

    我有点麻烦 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 回复  |  直到 9 年前
        1
  •  4
  •   chux    7 年前

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

    // 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);