I have a char array that I need to define in a function and return a char pointer, so i defined MAX which is the biggest size my char array can be according to my assigment and after I append part of it I want to copy it to char pointer so I can return it. the size of the part of the array that is full is i and I did malloc to with this size, then I did memcpy to copy only the part I want(strcpy copied also the ampty fields), but it still put in my result more weird stuff, how do I get rid of this?
Code:
char* result = (char*)malloc(i*sizeof(char));
if (result == NULL)
free(result);
memcpy(result, temp, i);
printf("%s", result);
return result;
Result of printf:
ccbcc²²²²U┤
while the result should be only "ccbcc".
iisstrlen(temp)then you allocate one too little (for the terminating null) and you copy one too little (that terminating null).tempis a string, usestrcpy(result, temp)instead ofmemcpyand make surei > strlen(temp). Also, do not cast the pointer returned bymallocin C programs.if (result == NULL) free(result);FYI:free(NULL)is a no-op, maybe better:if (result == NULL) { fprintf(stderr, "malloc error\n"); exit(EXIT_FAILURE); }char* result = (char*)malloc(i*sizeof(char));allocates 1-byte of memory. The only string you can store there is the empty-string (single'\0'char -- not very useful)