gpt4 book ai didi

C strcpy_s - 缓冲区太小 && 0 错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:39 25 4
gpt4 key购买 nike

我在这条线上有缓冲问题 strcpy_s(*(pWords + word_count), word_length, pWord); 我正在尝试从 argv[1] 中读取一个文件并打印出该文件中的每个单词及其出现的位置,但我不知道出了什么问题......?!?

int main(int argc, char* argv[])
{
char *delimiters = argv[2]; // Prose delimiters
char buf[BUF_LEN]; // Buffer for a line of keyboard input
size_t str_size = INIT_STR_EXT; // Current memory to store prose
char* filePath = argv[1];
FILE *fP ;
char* pStr = malloc(str_size); // Pointer to prose to be tokenized
*pStr = '\0'; // Set 1st character to null
fopen_s(&fP, filePath, "r");
fread(buf, BUF_LEN, 10, fP);





size_t maxWords = 10; // Current maximum word count
int word_count = 0; // Current word count
size_t word_length = 0; // Current word length
char** pWords = calloc(maxWords, sizeof(char*)); // Stores pointers to the words
int* pnWord = calloc(maxWords, sizeof(int)); // Stores count for each word

size_t str_len = strnlen_s(buf, BUF_LEN); // Length used by strtok_s()
char* ptr = NULL; // Pointer used by strtok_s()
char* pWord = strtok_s(buf, delimiters, &ptr); // Find 1st word

if (!pWord)
{
printf("No words found. Ending program.\n");
return 1;
}

bool new_word = true; // False for an existing word
while (pWord)
{
// Check for existing word
for (int i = 0; i < word_count; ++i)
if (strcmp(*(pWords + i), pWord) == 0)
{
++*(pnWord + i);
new_word = false;
break;
}

if (new_word) // Not NULL if new word
{
//Check for sufficient memory
if (word_count == maxWords)
{ // Get more space for pointers to words
maxWords += WORDS_INCR;
pWords = realloc(pWords, maxWords*sizeof(char*));

// Get more space for word counts
pnWord = realloc(pnWord, maxWords*sizeof(int));
}

// Found a new word so get memory for it and copy it there
word_length = ptr - pWord; // Length of new word
*(pWords + word_count) = malloc(word_length);
strcpy_s(*(pWords + word_count), word_length, pWord); // Copy to array
*(pnWord + word_count++) = 1; // Increment word count
}
else
new_word = true; // Reset new word flag

pWord = strtok_s(NULL, delimiters, &ptr); // Find subsequent word
}

最佳答案

strcpy_s在字符串末尾添加一个空字节。您需要 malloc(word_length+1)

关于C strcpy_s - 缓冲区太小 && 0 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com