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)

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
qwerty
  • 486
  • 1
  • 11
  • 37

2 Answers2

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    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 Apr 27 '15 at 11:48
  • @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. :-) – Sourav Ghosh Apr 27 '15 at 11:52
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);
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97