【发布时间】:2015-08-26 00:58:49
【问题描述】:
我在使用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;
}
【问题讨论】:
-
sizeof(char)-->sizeof(char*)抱歉@Martin,没有啤酒给你。 -
哈哈,这不公平:)
-
@user3386109 - 谢谢,不敢相信我没有发现。现在一切正常。 :)
-
使用模式
p = malloc(N * sizeof *p);有助于避免这个问题,视觉上你只需要在sizeof之后直接检查*,而不是必须将它匹配回一个cast几个字符到离开 -
而不是
int num_of_blocks = (int)ceil((double)string_length / 8);,你可以使用int num_of_blocks = (string_length + 7) / 8;来避免浮点数..
标签: c segmentation-fault malloc memcpy