【发布时间】:2021-12-27 18:36:46
【问题描述】:
我正在尝试编写一个程序,该程序将动态分配足够的空间来将所有单词存储在一个由空格分隔的一维字符数组中。 例如:
char *literal = "The quick brown fox";
char **words = { "The", "quick", "brown", "fox" };
我写的程序在尝试strncpy(str[buff_ptr],tok,strlen(tok));时不断出现段错误
我将在下面发布我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *mutableString(char *lit) {
int size = strlen(lit);
char *str = (char *)malloc(sizeof(char) * size);
strncpy(str, lit, size + 1);
return str;
}
int numTokens(char *str, const char *DELIM) {
char* clone = (char*)malloc(sizeof(char*));
strncpy(clone, str, strlen(str) + 1);
int count = 0;
for (char *tok = strtok(clone, " "); tok != NULL; tok = strtok(NULL, " "))
count++;
free(clone);
return count;
}
char **tokenize(char *str, const char *DELIM) {
printf("tokenize-------------------------\n");
int size = numTokens(str, DELIM);
//allocate space on heap for buffer
char **buff = (char **)malloc(size * sizeof(char *));
//get first word
char *tok = strtok(str, DELIM);
int buff_ptr = 0;
while (tok != NULL) {
strncpy(buff[buff_ptr], tok, strlen(tok) + 1);
printf("buff[%d]%s\n", buff_ptr, buff[buff_ptr]);
//increment to next word for storage
buff_ptr++;
//find next word in string
tok = strtok(NULL, DELIM);
}
for (int i = 0; i < size; i++) {
printf("%s\n", buff[i]);
}
//return 2D pointer
return buff;
}
int main() {
char *literal = "some literal string.";
//convert string to mutable string for strtok
char *str = mutableString(literal);
//set 2D pointer equal to the pointer address returned
char **no_spaces_str = tokenize(str, " ");
printf("%s\n", str);
for (int i = 0; i < numTokens(str, " "); i++) {
printf("%s\n", no_spaces_str[i]);
}
//free heap allocated memory
free(str);
free(no_spaces_str);
return 0;
}
lldb栈变量见附件:
【问题讨论】:
-
strlen给出chars 的数量,您需要分配+1的大小来满足空终止\0。 -
这是有道理的@TruthSeeker,但为什么会出现段错误,它不会将垃圾值读取到空终止符吗?
-
@KyleC。当您将 NUL 终止符写入您不拥有的内存时,您可能会出现段错误。当您读取未 NUL 终止的内存时,您可能会在获得 NUL 之前遇到不允许读取的内存
-
strncpy(buff[buff_ptr],tok,strlen(tok));行导致seg-fault因为在将单词复制到它之前没有分配任何内存 -
如果您负担得起,只需将 NUL 添加到您现有的字符串中并创建一个指向段的指针缓冲区。确保你只释放第一个。
标签: c split dynamic-memory-allocation c-strings strncpy