If I have a pointer to a message buffer how do I memcpy() into that buffer? For example say I have the following:
char **buffer;
char data[10]
memcpy(*buffer, data, 10);
But this doesn't seem to work and always crashes my program, however the compiler doesn't see to mind. Can someone please tell me why? Btw the reason I have a char **buffer is because its being passed as a parameter of the function.
The pointer variable buffer does not point to anything. You need to allocate memory and make buffer point to it. For instance:
buffer = malloc(sizeof(*buffer));
*buffer = malloc(10);
memcpy(*buffer, data, 10);
Related
I have some problems with a pointer. My idea was to pass a buffer to a function in order to store the return data in this buffer. But, I do not know if it will work.
void main()
{
char *buf = malloc(sizeof(char) *buf);
memset(buf, 0x00, BUF_SIZE);
sendCommand(buf);
}
sendCommand(char *buf)
{
write(fd, "some commands", strlen("some commands"));
readResponse(buf);
}
readResponse(char *buf)
{
read(fd, buf, nbytes);
}
I know there is no error handling up to now. And some variables are not well defined. It just depends on the passing buffer. Will I see the data that I get in readResponse() in my main function?
As in readResponse() as you read nbytes into buffer pointed by buf ,so you will get that data in main .
Some improvements to be done -
1. void main() -> int main(void) or int main(int argc, char *argv[])
2. char *buf = malloc(sizeof(char) *buf); -> char *buf = malloc(BUF_SIZE); // sizeof(char)=1 or maybe something you desire (not sure though what you want ??)
Note - remember to free allocated memory.
You have a remarkable number of significant problems in the code you presented, considering how short it is. Other answers have addressed those, though, and your question is not actually about any of them:
Will I see the data I get in readResponse() in my main function?
Yes, provided that argument buf is a pointer to an array large enough to accommodate nbytes bytes, and that the read() call in fact successfully reads any bytes, those bytes will afterward be visible in main() via the pointer it passed to readResponse(). More generally, if you pass a pointer as a function argument, the called function may manipulate the pointed-to object, including by modifying those parts of it that are not const. That's how the read() function itself is able to store the bytes it reads into your buffer, after all.
This won't do what you think it does:
char *buf = malloc(sizeof(char) *buf);
Did you mean to multiply with BUF_SIZE?
I am a novice programmer and I hagly appreciate any advice with my problem here.
I've made a procedure that gets a string in buffer and parses it in three cunks, separated by the first 2 ";".
What I tried to do is to pass 3 char pointers in where I will store my parsed string. But all I got in the calling function is memory garbage. What am I doing wrong?
void parseomensaje(char buf[256], char **idNodo, char **idMensaje, char **mensaje){
char *temp;
temp=(char *)malloc(sizeof(buf));
strcpy(temp, buf);
printf("\ntemp adentro de la funcion = %s\n", temp);
idNodo = strtok (temp,";");
idMensaje = strtok (NULL, ";");
mensaje = strtok (NULL, "\0");
printf("\nADENTRO\nidNodo: %s\nidMensaje: %s\nmensaje: %s", idNodo, idMensaje, mensaje);
}
this function is called this way:
char *idnod=NULL;
char *idmen=NULL;
char *men=NULL;
idnod=(char *)malloc(sizeof(buffer));
idmen=(char *)malloc(sizeof(buffer));
men=(char *)malloc(sizeof(buffer));
parseomensaje (buffer, &idmen, &idnod, &men);
after parseomensaje is executed buffer contains its original string, but idmen, idnod and men are blank.
I was reading from tutorials that pointers names are pointers itself, so it is the same thing as passing a parameter by reference, but in case of a string I need to pass the pointer address to a pointer to pointer...
I was reading it from here, but I'm still trying to figure it out.
PD: I apologize for my English, please feel free to point any mistakes in my writing. :)
This is incorrect:
char *temp;
temp=(char *)malloc(sizeof(buf));
as the array will degrade to a char* within the function, so only sizeof(char*) bytes are being allocated (typically 4 or 8 bytes). If the actually length of buf is greater than 4 or 8 bytes then the program has undefined behaviour as the strcpy() will be writing beyond the bounds of the array. Basically:
void parseomensaje(char buf[256], char **idNodo, char **idMensaje, char **mensaje){
is equivalent to:
void parseomensaje(char* buf, char **idNodo, char **idMensaje, char **mensaje){
If you are, as you say, a novice programmer I would recommend avoiding dynamic memory allocation until you get more comfortable with the language. Modify the program to use fixed sized arrays instead of dynamically allocated memory (and prevent writing beyond the bounds of the arrays). Once you have that working and fully understand it then attempt to use dynamically allocated memory.
First of all you have multiple memory leaks in your program. Consider freeing every single memory chunk you've allocated thanks to malloc once you don't need them anymore.
As regard your function:
void parseomensaje(char buf[256], char **idNodo, char **idMensaje, char **mensaje)
Why do you pass char** pointers on your function? Pass char* instead. Because strtok is declared this way:
char *strtok(char *str, const char *delim);
Moreover, you don't need to allocate any memory before calling parseomensaje since strtok returns a pointer on your own memory, not new allocated one.
numCheck is number between 1-1000. This code gives me a segfault only when I collect the results of sprintf in charcheck. If I simply use sprintf without using the results, I don't get a seg fault. What's happening here?
char * numString;
int charcheck = sprintf(numString, "%d", numCheck);
You need to provide your own memory for sprintf. Also, don't use sprintf, but rather snprintf:
char buf[1000] = {0};
snprintf(buf, 999, ....);
Alternatively you can allocate memory dynamically:
char * buf = new char[BUFSIZE];
snprintf(buf, BUFSIZE-1, ...);
/* ... */
delete[] buf;
The pointer given as the first parameter to sprintf is expected to point to a memory location where sprintf should write the formatted string.
In this case you didn't initialize numString to point to some memory you allocated for the formatted string. Since numString isn't initialized it might point anywhere, and in your case trying to write the formatted output to that location results in a segmentation fault.
The first argument to sprintf must point to a valid buffer. You have a char* but it points to garbage.
Change your code to:
char numString[80] = { };
int charcheck = sprintf(numString, "%d", numCheck);
So that numString actually points to a valid buffer (of 80 characters in this example, all elements of which are initialised to 0).
It would also be good to use snprintf so you can pass the size of your buffer to it, which will help prevent buffer overflows:
const int bufsize = 80;
char numString[bufsize] = { };
int charcheck = snprintf(numString, bufsize - 1, "%d", numCheck);
Notice that you subtract one from the buffer size that you pass to snprintf because you don't want it to use the very last slot, which you want to make sure is NULL to denote the end of the string.
You need to allocate space for the result such as
char numString[50];
int charcheck = sprintf(numString, "%d", numCheck);
In your case the interal workings of sprintf are trying to reference NULL which is the default value for a pointer in your case.
The most straightforward thing to do is to use an array as above, e.g.,
char numString[80] = { };
suggested by Seth, Jesus and Kerrek.
I think the last answer from sth is a good explanation: "the first parameter to sprintf is expected to point to a memory location where sprintf should write the formatted string." So apart from using an array of characters, which would force the allocation of memory for the string, you can also use this:
char *numstring = (char*) malloc(80);
This should let you explicitly free the allocated memory when it is no longer needed.
I radically re-edited the question to explain better my application, as the xample I made up wasn't correct in many ways as you pointed out:
I have one pointer to char and I want to copy it to another pointer and then add a NULL character at the end (in my real application, the first string is a const, so I cannot jsut modify it, that's why I need to copy it).
I have this function, "MLSLSerialWriteBurst" which I have to fill with some code adapt to my microcontroller.
tMLError MLSLSerialWriteBurst( unsigned char slaveAddr,
unsigned char registerAddr,
unsigned short length,
const unsigned char *data )
{
unsigned char *tmp_data;
tmp_data = data;
*(tmp_data+length) = NULL;
// this function takes a tmp_data which is a char* terminated with a NULL character ('\0')
if(EEPageWrite2(slaveAddr,registerAddr,tmp_data)==0)
return ML_SUCCESS;
else
return ML_ERROR;
}
I see there's a problem here: tha fact that I do not initialize tmp_data, but I cannot know it's length.
For starters, you are missing a bunch of declarations in your code. For example, what is lungh? Also, I'm assuming you initialized your two pointers so they point to memory you can use. However, maybe that's not a safe assumption.
Beyond that, you failed to terminate your from string. So getting the length of the string will not work.
There seems to be numerous errors here. It's hard to know where to start. Is this really what your actual code looks like? I don't think it would even compile.
Finally, there seems to be a bit of confusion in your terminology. Copying a pointer is different from copying the memory being pointed to. A pointer is a memory address. If you simply copy the pointer, then both pointers will refer to the same address.
I would create a copy of a string using code similar to this:
char *from_string = "ciao";
char *to_string;
int len;
len = strlen(from_string);
to_string = (char *)malloc(len + 1);
if (to_string != NULL)
strcpy(to_string, from_string);
Be fully aware that you do not want to copy a pointer. You want to copy the memory that is pointed to by the pointer. It does sound like you should learn more about pointers and the memory environment of your system before proceeding too much farther.
When you say tmp_data = data, you are pointing tmp_data to the same memory pointed to by data. Instead, you need to allocate a new block of memory and copy the memory from data into it.
The standard way to do this is with malloc. If you do not have malloc, your libraries may have some other way of acquiring a pointer to usable memory.
unsigned char * tmp_data = malloc(length + 1);
if(tmp_data != 0) {
memcpy(tmp_data, data, length);
tmp_data[length] = 0;
// ...
free(tmp_data);
}
You could also use a fixed-size array on the stack:
unsigned char tmp_data[256];
if(length >= sizeof(tmp_data)) length = sizeof(tmp_data) - 1;
memcpy(tmp_data, data, length); // or equivalent routine
tmp_data[length] = 0;
C99 introduced variable-length arrays, which may be what you seek here, if your compiler supports them:
unsigned char tmp_data[length];
memcpy(tmp_data, data, length); // or equivalent routine
tmp_data[length] = 0;
I'm specifically focused on when to use malloc on char pointers
char *ptr;
ptr = "something";
...code...
...code...
ptr = "something else";
Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?
As was indicated by others, you don't need to use malloc just to do:
const char *foo = "bar";
The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.
So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.
const char *foo = "bar";
char *bar = strdup(foo); /* now contains a new copy of "bar" */
printf("%s\n", bar); /* prints "bar" */
free(bar); /* frees memory created by strdup */
Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.
char *foo = malloc(sizeof(char) * 1024); /* buffer for 1024 chars */
snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */
printf(foo); /* prints "foo - bar" */
free(foo); /* frees mem from malloc */
malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);
malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.
Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).