Reputation: 49
#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);
}
Here is a piece of C code ,that sometimes runs, sometimes doesn't run and gives an error Thread 1: signal SIGABRT.
Debug (23028,0x1000ebe00) malloc: *** error for object 0x1007af200: pointer being realloc's d was not allocated Debug (23028,0x1000ebe00) malloc: *** set a breakpoint in malloc_error_break to debug(23028,0x1000ebe00) malloc: *** set a breakpoint in malloc_error_break to debug(23028,0x1000ebe00 (lldb)
And focus the cursor on line 37:
str1 = realloc((char *)str1,realSize);
I can't solve the problem
Upvotes: 1
Views: 130
Reputation: 36441
Problem is within this loop:
while((argv = va_arg(args,const char *)) && argv != NULL) {
strcats((char *)result,argv);
}
strcats
reallocates the memory associated to result
(parameter named str1
) but realloc
may change the address. You correctly return the new address but never use it, so result
never change. Then at a given time, when realloc
moves the data to another place, the former is no more valid, at the next loop the bad address is then sent again.
Change to :
while((argv = va_arg(args,const char *)) && argv != NULL){
result = strcats(result,argv);
}
Upvotes: 0