分段错误和在指向未分配对象的指针上调用的'free'



我目前正在编写一个程序来简单地反转C中的字符串。然而,当我试图将我创建的临时字符串的内容复制到原始字符串中时,我遇到了分段错误。此外,当我试图释放为测试字符串分配的内存时,我会收到一个警告,上面写着"在指向未分配对象的指针上调用的"free";这是我的代码:

void reverseString(char* str, size_t size) {
char *temp = (char*) malloc(sizeof(str) + 1);
int j = size;
for (int i = 0; i < size; i++) {
temp[i] = str[j];
j--;
}
for (int i = 0; i < size; i++) {
str[i] = temp[i];
}
free(temp);
return;
}

int main() {
char* result = (char*)(malloc(sizeof(char) * 10));
result = "Forty-two";
reverseString(result, strlen(result));
printf("%s", result);
free(result);
result = NULL;
return 0;
}

在第二行中,您应该使用strlen而不是sizeof,因为否则您将为字符指针分配空间,并且您需要更多的空间。

  • sizeof(str(返回指针的大小,而不是文字的长度
  • 数组索引从0开始。这就是为什么j应该以(size-1(开头
  • 您正在从堆中分配内存,请在执行某些操作之前使用memset

@bereal已经说过,如果你想了解更多,请查看:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char* result = (char*)(malloc(sizeof(char) * 10));
memset(result, 0, 10);
printf("Addr of result var : %p n", result);
result = "Re-assign";
printf("Addr of result var : %p n", result);
return 0;
}

也许我的解决方案给你一个想法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverseString(char** str, size_t size) {
char *temp = (char*) malloc(size + 1);
memset(temp, 0, size + 1);
int j = size - 1;
for (int i = 0; i < size; i++) {
temp[i] = str[0][j];
j--;
}
//Change addr of holding str
*str = temp;
return;
}

int main() {
char* result = "Forty-two";
reverseString(&result, strlen(result));
printf("%s", result);
//result holds same addr with temp
free(result);
return 0;
}

但有一些方法可以更准确地解决这个问题。

最新更新