【发布时间】:2021-06-08 15:59:28
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/uio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdarg.h>
void debug(void);
char * string(const char * );
char * strcats(const char * ,const char * );
char * strspe(const char *, ...);
int isDir(const char *);
int main(void){
debug();
return 0;
}
void debug(void){
char * str = "ssssss";
str = string("abcdef");
char * hello;
hello = strspe(str,"hello","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world","world",NULL);
printf("hello: %s ,Address: %p\n",hello,(char *)hello);
}
char * string(const char * str){
return strcpy(malloc(strlen(str) * sizeof(char) + sizeof(char)),str);
}
char * strcats(const char * str1,const char * str2){
int realSize = (int)strlen(str2) * sizeof(char) + (int)strlen(str1) * sizeof(char) + sizeof(char);
str1 = realloc((char *)str1,realSize);
strcat((char *)str1,str2);
return (char *)str1;
}
char * strspe(const char * format, ...)
{
va_list args;
const char * argv;
char * result = string(format);
//free((char*)format);
va_start(args, format);
while((argv = va_arg(args,const char *)) && argv != NULL){
strcats((char *)result,argv);
}
va_end(args);
return result;
}
int isDir(const char *filename){
return (access(filename, 0) == 0);
}
这是一段C代码,有时运行,有时不运行并报错Thread 1: signal SIGABRT。
调试 (23028,0x1000ebe00) malloc: *** 对象 0x1007af200 的错误:未分配 realloc 的 d 指针 调试 (23028,0x1000ebe00) malloc: *** 在 malloc_error_break 中设置断点为 debug(23028,0x1000ebe00) malloc: *** 在 malloc_error_break 中设置断点为 debug(23028,0x1000ebe00 (lldb)
并将光标聚焦在第 37 行:
str1 = realloc((char *)str1,realSize);
我无法解决问题
【问题讨论】:
-
strcats((char *)result,argv);:strcats函数返回新指针,但您不使用它。应该是result = strcats(result, argv)。不需要演员表。 -
我们不知道第 37 行在哪里。我们需要计算您的 sn-p 中的行数吗?另外,当您预期崩溃转储时,您发现了什么?
-
欢迎来到 SO。
strcats返回某些值可能有某种原因。打电话后不理你的理由是什么? -
同样
strcats的第一个参数不应该是const,因为那个地址的内存被修改了(realloc之后那个内存就不再有效了)。 -
谢谢。我想我应该清醒一下,再看一遍