嘿伙计们,这是我第一次使用堆栈溢出:D 我收到此错误:
Unhandled exception at 0x0105F338 (ucrtbased.dll) in Assignment_5.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD.
Exception thrown at 0x0105F338 (ucrtbased.dll) in Assignment_5.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD.
这是主要的:
void Test2(char* arr[], int size_arr, char* str, int size_res, char* str_cmp)
{
int size_res_new;
char** tempStringArr = LowerSTR(arr, size_arr, str, &size_res_new);
if (tempStringArr == NULL)
{
printf("Can't allocate arr (-4)\n");
return;
}
if (size_res_new != size_res)
{
printf("The amount of string is not correct (-4)\n");
return;
}
for (int i = 0; i < size_res; i++)
{
if (strcmp(tempStringArr[i], str_cmp) == 0)
{
return;
}
}
printf("No String: %s (-4)\n", str_cmp);
}
这是函数:
char** LowerSTR(char* arr[], int size_arr, char* str, int* size_res)
{
char** newArr = NULL, counter=0;
newArr = (char**)malloc(size_arr * sizeof(char*));
if(newArr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
for(int i=0; i<size_arr; i++)
{
if (strcmp(arr[i], str) < 0) {
newArr[counter] = (char*)malloc(sizeof(char) * strlen(arr[i]));
if (newArr[counter] == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
strcpy(newArr[counter], arr[i]);
}
else
counter++;
}
*size_res = size_arr - counter;
newArr = (char**)realloc(newArr, sizeof(char*) * (*size_res));
return newArr;
}
最佳答案
newArr[counter] = (char*)malloc(sizeof(char) * strlen(arr[i])); // allocate strlen(arr[i]) bytes
if (newArr[counter] == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
strcpy(newArr[counter], arr[i]); // copy 1+strlen(arr[i]) bytes. oops.
您分配了 strlen(arr[i])
字节,但随后尝试将 arr[i]
复制到您分配的缓冲区中。但它的一个字节太少了,因为字符串末尾有一个 null 字符。您需要再分配一个字节。像 valgrind 这样的工具应该会告诉你这一点。
关于C - 无法使用指针执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492665/