gpt4 book ai didi

C - 无法使用指针执行函数

转载 作者:行者123 更新时间:2023-11-30 19:00:30 25 4
gpt4 key购买 nike

嘿伙计们,这是我第一次使用堆栈溢出: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/

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