0

I am first concatenating a series of elements in an auxiliary char array to then assign the concatenated array to the pointer. The problem comes when assigning this char array to the pointer, where it produces a segmentation fault.

My approach was the following one:

char aux_name [12];
char * name = (char *) malloc(sizeof(char)*13);
int i;

for(i = 0; i < 5; i++){
    sprintf(aux_name, "id_%i", i);
    *name = (void *) (intptr_t) aux_name; //Conflict line

   //Do something with variable name (it is required a pointer)

}
2
  • 4
    Standard Warning : Please do not cast the return value of malloc() and family in C. Commented Apr 27, 2015 at 11:16
  • Side note: what's the point in performing the exact same assignment 5 times??? Commented Apr 27, 2015 at 11:46

2 Answers 2

1

You don't assign a pointer value to an already malloc()-ed pointer, you'll be facing memory-leak there. You have to use strcpy() to achieve what you want.

OTOH, if you don't allocate memory dynamically, then you can assign the pointer like

name = aux_name;

That said,

I am first concatenating a series of elements in an auxiliary char array

Well, you're not. you're simply overwriting the array every time in every iteration. What you need to do is

  1. Collect the return value of sprintf() every time.
  2. next iteration, advance the pointer to buffer by that many locations to concatinate the new input after the previous one.

Note / Suggestion:

  1. do not cast the return value of malloc() and family in C.

  2. sizeof(char) is guranteed to be 1 in c standard. You don't need to use that, simply drop that part.

Sign up to request clarification or add additional context in comments.

2 Comments

The remark about sizeof(char) is subjective. Some believe it should be there to make all malloc calls consistent. To use it or not is personal preference, there's no right or wrong (unlike casting the result of malloc, which is always bad/superfluous).
@Lundin sir, you're very right. But just as per one of the logics behind not casting malloc() result [the It makes you repeat yourself, which is generally bad. part], we can suggest not to use sizeof(char), isn't it? However, I updated my remark. Hope it is ok now. :-)
0

You can't do that, and you don't really need to, this would work

size_t nonConstanSizeInBytes = 14;
char *name = malloc(nonConstanSizeInBytes);

snprintf(name, 13, "id_%i", i);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.