0

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".

6
  • If i is strlen(temp) then you allocate one too little (for the terminating null) and you copy one too little (that terminating null). Commented Dec 24, 2019 at 15:21
  • temp's size is 3000 but only i-1 fileds have values. the strlen comment return me 3000 and I dont want that.. Commented Dec 24, 2019 at 15:27
  • If temp is a string, use strcpy(result, temp) instead of memcpy and make sure i > strlen(temp). Also, do not cast the pointer returned by malloc in C programs. Commented Dec 24, 2019 at 15:37
  • 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); } Commented Dec 24, 2019 at 15:50
  • 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) Commented Dec 24, 2019 at 16:17

1 Answer 1

1

Instead of printing like this: printf("%s", result);

you should be printing only indexes which are initialized and contains value:

for(int k=0;k<i;k++){
  printf("%c", s[k]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this one at the begining and it didnt work, but now suddenly it works! thanks:)
@Ran121 great !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.