I feel confusion about bus error in string (C)

流过昼夜 提交于 2019-11-28 11:52:07

The difference here is that

 char *strBase = "acbdefg"; 

will place acbdefg in the read-only parts of the memory and making strBase a pointer to that, making any writing operation on this memory illegal.

It has no name and has static storage duration (meaning that it lives for the entire life of the program); and a variable of type pointer-to-char, called strBase, which is initialised with the location of the first character in that unnamed, read-only array.

While doing:

char strBase[8] = "acbdefg";

puts the literal string in read-only memory and copies the string to newly allocated memory on the stack.

So this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialized data segment" that is loaded from the executable file into write able memory when the program is run.

Making

strBase[0] = 'x';

legal.

Your problem is one of memory allocation. You need space to store your characters. When you wrote:

char strBase[8] = "acbdefg";

you created automatic storage (often called the stack) and initialized it with a string of characters. But when you wrote:

char *strBase = "acbdefg";

you created a pointer and pointed it at a constant string. The compiler puts that in a part of memory that is marked as read-only. If you try to change that it will result in a memory access violation.

Instead you could do something like:

const char* strData = "acbdefg";
int size = 1024;
char *strBase = (char*)malloc(size);
strncpy(strBase, strData, size);
ProcessString(strBase);
free(strBase);

The most likely cause is that

char strBase[8] = "abcdefg";

causes the compiler to reserve memory for an eight-character array, and initializes it with the value "abcdefg\0". In contrast,

char *strBase = "abcdefg";

only reserves memory for a pointer, initialized with the address of the string. "abcdefg" is a constant string, and as a result, the compiler stores it in a section of memory that gets marked read-only. Attempting to modify read-only memory causes a CPU fault.

Your compiler should be giving you a warning about const mismatch in the second case. Alternatively, your compiler may have a setting that changes the read-only-ness of constant strings.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!