C - 为什么此截图代码在此行的第二次迭代时触发断点 "*(str_arr + i) = (char*)calloc((strlen(temp_str) + 1), sizeof(char));"



只是尝试将N字符串扫描到数组并动态分配它们

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3
#define MAX_STR_LEN 20
void main(void) {
char* str_arr[N] = { '' };
char temp_str[MAX_STR_LEN] = { '' };
for (size_t i = 0; i < N; i++)
{
//scan string
fgets(temp_str, MAX_STR_LEN, stdin);
strtok(temp_str, "n");
// next line of code triggers breakpoint at second iteration
*(str_arr + i) = (char*)calloc((strlen(temp_str) + 1), sizeof(char));
if (!(str_arr + i))
{
printf("Could not allocate memoryn");
return 1;
}
//copy temporary string to dedicated string
strcpy_s(*(str_arr + i), sizeof(temp_str), temp_str);
}
printf("n");
system("PAUSE");
}

一些观察:

  • 您没有分配sizeof(temp_str).您已分配strlen(temp_str)+1.因此,第一个strcpy_s将导致缓冲区溢出,这就是为什么在循环的第二次迭代中出现问题的原因。
  • 语句if (!(str_arr +i))不检查指针 刚刚分配
  • *(str_arr + i)str_arr[i]相同,后者更容易 对于阅读代码的人
  • 在第char* str_arr[N] = { '' };行中,你声明了一个指针数组,但你用一个字符常量 () 初始化,这是一个int。初始值设定项应为NULL指针。
  • 此答案显示了从缓冲区中删除换行符的更好方法。strtok的问题在于,如果用户输入空行,它不会删除换行符。

考虑到这一点,这是我建议的解决方法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3
#define MAX_STR_LEN 20
int main(void) {
char* str_arr[N] = { NULL };
char temp_str[MAX_STR_LEN] = { '' };
for (size_t i = 0; i < N; i++)
{
//scan string
if (fgets(temp_str, MAX_STR_LEN, stdin) == NULL)
{ 
printf("Not enough lines of inputn");
return 1;
}
temp_str[strcspn(temp_str, "n")] = '';
size_t length = strlen(temp_str) + 1;
str_arr[i] = (char *)calloc(length, 1);
if (!str_arr[i])
{
printf("Could not allocate memoryn");
return 1;
}
//copy temporary string to dedicated string
strcpy_s(str_arr[i], length, temp_str);
}
printf("n");
system("PAUSE");
}

最新更新