Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are string arguments in C dynamically allocated?

Tags:

c

string

Let's say I have a function with the following specification:

void example(char* str)

If I pass in a string argument, such as:

example("testing");

Is the value of "testing" dynamically allocated on the heap, so I'll be able to use it after the scope that made the function call to "example" is destroyed (and need to free it later), or is it a local variable on the stack, so I'll need to make a new string using malloc and store the value in there if I want it to persist in, say, a hashmap?

Thanks.

like image 566
Paul B Avatar asked Jun 16 '26 09:06

Paul B


1 Answers

When you write "testing" in your program, it will be compiled as a string literal, and room for it will be allocated during compile time. When you get a pointer to it, it's a pointer to that place in memory. You don't need to allocate it with malloc(), and you also should not free() it. But it's also not a good idea to try to modify its content, because the compiler will likely put it in a readonly area (that is, it's compiled as a constant) -- the following program, for example, crashes on my Linux desktop:

#include <stdio.h>
int main() {
    char *a = "abc\n";
    a[0]='X';
    printf(a);
    return(0);
}
like image 88
Jay Avatar answered Jun 17 '26 21:06

Jay